Hi, I'm building a C wrapper for my Fortran simulator to be used in Python. I made this function that takes the number of an element and returns its name:
type(c_ptr) function get_elem_name(i) bind(C, name="get_elem_name") #IFDEF DLL !DEC$ ATTRIBUTES DLLEXPORT :: get_elem_name #ENDIF use ELEMENTS, only: elemname, nbelem implicit none integer(c_int), INTENT(IN), value :: i character(len=21,kind=c_char) :: returnval returnval=''//C_NULL_CHAR if(i<=nbelem .and. i>0)returnval=trim(elemname(i))//C_NULL_CHAR get_elem_name = C_LOC(returnval) end function get_elem_name
It is called from Python as:
import ctypes mylib = ctypes.CDLL("mylib.dll") mylib.init() # initialize simulator mylib.get_elem_name(1) # get the name of the first element
It works perfectly for the first 200 calls or something. After that, it randomly returns an empty string (''). I cannot get my head around the problem. Could it be that retval is automatically allocated inside Fortran and then the pointer passed to Python? Could that create an issue?
Thanks for any help.