- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
Link Copied
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
@ferrad1 ,
See this thread for a worked out example, albeit with different parameters.
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
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!
- Subscribe to RSS Feed
- Mark Topic as New
- Mark Topic as Read
- Float this Topic for Current User
- Bookmark
- Subscribe
- Printer Friendly Page