Intel® Fortran Compiler
Build applications that can scale for the future with optimized code designed for Intel® Xeon® and compatible processors.
28455 Discussions

Allow variables to be modifiable in Fortran from a Python call

ferrad1
New Contributor I
450 Views

 

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.  Must be something in the syntax of the first argument in the Python call.

0 Kudos
3 Replies
FortranFan
Honored Contributor II
408 Views

@ferrad1 ,

 

See this thread for a worked out example, albeit with different parameters.    

https://community.intel.com/t5/Intel-Fortran-Compiler/Passing-by-reference-a-Python-string-to-Fortran-function/m-p/1297543/highlight/true#M156738

 

Concept is generally the same: use argtypes to inform the ctypes foreign library in Python as to the parameters in the Fortran call.

https://docs.python.org/3/library/ctypes.html#ctypes._FuncPtr.argtypes

 

Steve_Lionel
Honored Contributor III
408 Views

I don't know Python, but it sounds as if Python is passing a temporary copy of x, which is then discarded. From the snippet of Fortran you showed, any changes to x would be reflected in what was passed. It would be interesting to see if you could duplicate this with a C routine instead of Fortran. Of course, not having a complete example makes it difficult to speculate further.

ferrad1
New Contributor I
297 Views

Yes, you're probably correct.  I got this syntax from an expert:

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

It works, don't ask me how!

 

0 Kudos
Reply