Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cython, C and Fortran

I would like to ask your help about calling fortran function through C functions. These C functions will be used in python code through cython. Putting things together, I have this scheme:

Cython Module -> C function -> Fortran, where -> means "calls".

Currently I managed to call the C function from cython, but I am having an hard time calling the fortran function. Can you help me?(an simple example would be great).

Thanks in advance. Edit: I am using gcc 4.1.2. And gfortran

like image 561
nunolourenco Avatar asked Dec 29 '22 04:12

nunolourenco


1 Answers

The link in the first answer describes outdated methods. It has become much easier to call Fortran from C, or C from Fortran with the addition of the ISO C Binding to Fortran. Using this Fortran language feature instructs the Fortran compiler to emit executable code that is binary compatible with C. The programmer doesn't have to "hack" the connection and since it is part of the language is it compiler and platform independent. Technically the ISO C Binding is part of Fortran 2003 but it has been available for several years in numerous compilers, e.g., gfortran since version 4.3 and Intel ifort.

To call a Fortran subroutine or function from C, you declare the Fortran subroutine or function with the bind C option and use the C-compatible types provide in the binding for the declarations of the arguments. There are examples in the gfortran manual under "Mixed Language Programming". Since the ISO C Binding is a part of the language, this section of the manual is largely compiler independent. There are other examples in previous answers here on Stack Overflow and elsewhere on the web.

Here is a quick code fragment (untested) of a Fortran subroutine declaration of a subroutine to be called from C:

subroutine test ( varint1, varflt2 )  bind ( C, name="MyTest" )

   use iso_c_binding

   integer (kind=c_int32_t), intent (in) :: varint1
   real (kind=c_float), intent (out) :: varflt2

The bind C name "MyTest" overrides the Fortran name -- it is case sensitive, unlike Fortran. No need to worry about underscores! The variable types should be obvious ... see the gfortran manual or elsewhere for whats available.

like image 144
M. S. B. Avatar answered Dec 30 '22 17:12

M. S. B.