Moonwalk
Moonwalk

Reputation: 152

Calling Fortran from Python using CFFI

I am trying to reproduce this example on Windows. Here are the corresponding fortran codes

fortran_wrapper.f90

MODULE FORTRAN_WRAPPER

USE ISO_C_BINDING, ONLY: C_INT
USE YOUR_FORTRAN_MODULE

IMPLICIT NONE

CONTAINS
  SUBROUTINE C_WRAPPER_YOUR_SUBR(ARG1) BIND(C, NAME = "C_WRAPPER_YOUR_SUBR")

     INTEGER(C_INT), INTENT(IN), VALUE :: ARG1  

     CALL YOUR_SUBR(ARG1)

  END SUBROUTINE C_WRAPPER_YOUR_SUBR

END MODULE FORTRAN_WRAPPER

fortran_code.f90

 MODULE YOUR_FORTRAN_MODULE

  CONTAINS
  
    SUBROUTINE YOUR_SUBR(ARG1)

     IMPLICIT NONE

     INTEGER, INTENT(IN) :: ARG1

     WRITE(*,*) 'The values is: ', ARG1

   END SUBROUTINE YOUR_SUBR

 END MODULE YOUR_FORTRAN_MODULE

Here is the corresponding calling python code

python_prog.py

from cffi import FFI
import os
ffi = FFI()
dll_path = os.path.join(os.path.dirname(__file__), 'dll_name.dll')
lib = ffi.dlopen(dll_path)

ffi.cdef("void C_WRAPPER_YOUR_SUBR(int arg1);")

arg1 = 1

lib.C_WRAPPER_YOUR_SUBR(arg1)

The dll_name.dll was created using intel fortran compiler in the following way

ifort /dll fortran_code.f90 fortran_wrapper.f90 /exe:dll_name.dll

After running the python python_prog.py I got the following error

AttributeError: function/symbol 'C_WRAPPER_YOUR_SUBR' not found in library 'dll_name.dll': error 0x7f

I would appreciate any help.

Upvotes: 2

Views: 293

Answers (1)

Armin Rigo
Armin Rigo

Reputation: 12990

(Copying here the answer from this external forum) On Windows, you need to make the function exported from the DLL. In other words, whereas on POSIX systems all non-static functions are exported by shared libraries (by default), it does not work like this on Windows. In C, you would need either to use a .def file, or say in the C source:

__declspec(dllexport) int myfunction(int a) {
   ...
}

(Also copying here your comment) The Fortran equivalent seems to be to add this to your .f90 file:

!DEC$ ATTRIBUTES DLLEXPORT :: C_WRAPPER_YOUR_SUBR

Upvotes: 1

Related Questions