Using Fortran to Call C ++ Functions

I am trying to get the FORTRAN code to call a couple of C ++ functions that I wrote (one of them is c_tabs_). Binding and everything works fine as long as I call non-class functions.

My problem is that the functions that I want the FORTRAN code to call belong to the class. I looked at the character table using nm, and the function name is something ugly:

00000000 T _ZN9Interface7c_tabs_Ev 

FORTRAN will not allow me to call a function under this name due to the underscore at the beginning, so I do not understand.

The symbol for c_tabs, if it is not in the class, is quite simple, and FORTRAN has no problems with it:

 00000030 T c_tabs_ 

Any suggestions? Thanks in advance.

+4
source share
4 answers

If you are creating a C ++ C-style interface routine (as described above), you can use the Fortran 2003 ISO C binding function to call it. When binding to ISO C, you can specify the name of the subroutine and (within) the C types and invoke the agreement (reference, by value) of the arguments and return the function. This method works well and has the advantage of being standard and therefore dependent on the compiler and platform, in contrast to the old Fortran C methods. ISO C binding is supported by many Fortran 95 compilers, such as gfortran> = 4.3.

+3
source

The name is garbled, which the C ++ compiler does to execute functions, such as function overloading and type binding. Honestly, you can hardly call member functions from FORTRAN (because FORTRAN cannot create instances of the C ++ class, among other reasons) - you must express your interface in terms of the C API, which will be accessible from anywhere .

+7
source

You will need to create a c-style and "extern" interface. C ++ manages method names (and overloaded functions) for binding. It is known that it is difficult to associate C ++ with anything other than C ++. There are β€œmethods,” but I highly recommend that you simply export the C interface and use the standard tools available in Fortran.

+4
source

You need to create extern "C" wrappers to handle all FORTRAN details that invoke C ++, the name mangling is the most obvious.

 class foo { public: int a_method (int x); } extern "C" int foo_a (foo * pfoo, int * px) { if (NULL == pfoo) return 0; else return pfoo->a_method (*px); } 

Note that FORTRAN compilers pass all arguments by reference, but not by value. (Although they tell me that, strictly speaking, this is not part of the FORTRAN standard.)

+3
source

Source: https://habr.com/ru/post/1304808/


All Articles