Allow variables to be modifiable in Fortran from a Python call

I am calling Fortran from Python as follows:

import ctypes as ct
lib = ct.CDLL('x64\\Debug\\main2.dll')
f = getattr(lib,'MAIN2_MOD_mp_MAIN2')
f.restype = None
x = [2.0, 0.0]
def fun(x):
   objf = c_double(0.0)
   f((c_double * len(x))(*x), byref(objf))
   return objf

The Fortran is:

module main2_mod
  contains
    !dec$ attributes dllexport :: main2
    subroutine main2(x,f)
    implicit none
    real(8), intent(inout) :: x(*)
    real(8), intent(out) :: f

This works fine when x is not changed in the Fortran. However when I change x, the new values do not get returned to Python.

I strongly suggest you to use numpy.ctypeslib.ndpointer

You can see an example in:

As it is shown pass the input inside a call to np.ascontiguousarray

def ppp(x):
   x = np.ascontiguousarray(x, dtype=...)
1 Like

I didn’t want to try something completely new, instead I changed the list to numpy arrays. The syntax for the Fortran call for the (inout) variable is:

f(x.ctypes.data_as(ct.POINTER(ct.c_double)), ct.byref(objf))