Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28446 Discussions

Call a C++ function from a Fortran module

wisperless
Beginner
378 Views

I am wonderingthat calling a C++ function from a Fortran subroutine is the same way ascalling from a Fortran subroutine which inside a module?

C++ code

extern
"C" void FORTRAN_CALL_C (int *i,int*j)
{
*i=1;
*j=5;
printf("This is Called from Fortran!
");
}
Fortran Code 1 (calling from a subroutine)
subroutine F1(INT_ARG, STR_IN, STR_OUT)
CALL FORTRAN_CALL_C(INT_ARG, STR_IN)
end subroutine
F1
Fortran code 2 (calling from a module)
MODULE FDLL 
contains
subroutine F1(INT_ARG, STR_IN, STR_OUT)
   CALL FORTRAN_CALL_C(INT_ARG, STR_IN)
end subroutine
F1
I got a message error showing

2>FDLL .obj : error LNK2019: unresolved external symbol FORTRAN_CALL_C referenced in function FDLL_mp_F1

Thank you in advance!
0 Kudos
5 Replies
wisperless
Beginner
378 Views
I forgot to mention that the Fortran code is inside a DLL which is called from another C++ function.
0 Kudos
Steven_L_Intel1
Employee
378 Views
I don't see anything wrong from what you have posted here. You should make sure that the object file from the C compilation is being linked in with the DLL. There is no difference in how a C routine is called from within a module or not within a module.
0 Kudos
wisperless
Beginner
378 Views

Steve, Thanks you. After I added an interface in the top of the module section, the code works. My another problem is how to define dynamic allocated array in the interface.

module
EXAMP
INTERFACE
SUBROUTINE FORTRAN_CALL_C(INT_array, INT_array2)
!DEC$ ATTRIBUTES REFERENCE :: INT_array, INT_arry2
INTEGER INT_array, INT_arry2 ===> How to define a dynamic allocated array here???
END SUBROUTINE
END INTERFACE
.....
end module.
Since in the Fortran I have an dynamic allocated array that 
pass to C++ function.
Inside the fortran code:
integer noofindex
noofindex=10

allocate(INT_array(noofindex),stat=error)

if(error.ne.0) then

write(911,*) "allocate INT_array error"

stop

endif

INT_array(:) = 0

Thank you very much!

0 Kudos
Steven_L_Intel1
Employee
378 Views
That depends on what the C code does. If it just receives a pointer to the array and uses [] notation to index it, then use DIMENSION(*) in the Fortran interface. If the C code understands Fortran array descriptors and uses the descriptor fields (unlikely), then use DIMENSION(:).
0 Kudos
wisperless
Beginner
378 Views
Thank you very much! My code works now.
0 Kudos
Reply