I am a fresh in programming, I wanna to call a fortran function in my c++ code. the thing is I dont know how to pass a fortran character*81 array to my c++.
fortran code is like:
subroutine func01(a)
implicit none
character*81 a(2)
write(*,*) a(1)
write(*,*) a(2)
end
c++ code is like:
#include <iostream>
extern "C"{
void func01_( const char **a );
}
int main()
{
const char *a[2];
a[0]="Hello world!";
a[1]="This is a test!";
func01_(a);
return 0;
}
I bascially tested my fortran code using this
program pro01
character*81 a(2)
a(1)='Hello world!'
a(2)='This is a test!'
call func01(a)
end program pro01
'func01(a)' works well.
thanks to @PaulMcKenzie, I corrected some fool problems.....
However, when i compiled cpp code, the result went like messy codes like:
7
@L
@��n��@�UH�j��FP
@��n���U�շ�=��U�ྼ��� @��
what should I do?
Here is a portable solution to pass an array of arbitrary length strings from C to Fortran.
I used a C++ file very similar to your own:
The only changes above are the initialization of the character arrays and removing the not-so-portable underscoring of the Fortran function. Instead we will be using standard C interoperability provided by Fortran 2003. The Fortran implementation of
func01
becomes:The
bind
attribute is what gives us interoperability with C for the function name and we are using C types for variables. The variablecstrings
will take an array of 2 pointers, or in C,*[2]
or**
. The bulk of the procedure is an interface block which lets us call the standard C library routinestrlen
to make our life easier with the following calls toc_f_pointer
which translates a C pointer to a Fortran pointer.When compiled and run, the output, as expected, is:
Compiled and tested with gcc 5.1.0.
The following code seems to work for gcc4 on Linux(x86_64), but it is not clear whether it is also valid for other platforms. (As suggested above, C-interoperability of modern Fortran may be useful.)
func01.f90
main.cpp
Compile
Result