Returning array when calling Fortran from Python using Ctypes



Answers

Question

How do you return arrays from Fortran to Python using ctypes?

As an example, I pass in an array (length 5) from Python to Fortran. An output array is created with the same values. Then, it is passed back to Python. Within Fortran, the values are correct, but after being sent back to Python, they are not. What about my setup is not allowing the array to pass correctly?

My Fortran code (e.g., test.f) contains the following:

SUBROUTINE mySub(inArray, lenInOut, outArray) BIND(C)

USE ISO_C_BINDING
IMPLICIT NONE

INTEGER(C_INT), INTENT(IN), VALUE :: lenInOut
REAL(C_DOUBLE), DIMENSION(lenInOut), INTENT(IN) :: inArray
REAL(C_DOUBLE), DIMENSION(lenInOut), INTENT(OUT) :: outArray

print *, "outArray from within Fortran"
do i = 1, lenInOut
  outArray(i) = inArray(i)
  print *, outArray(i)
end do
return
end subroutine mySub

This is compiled as a .so:

ifort -g -O0 -fpic -traceback -c -o "test.o" "../test.f"
ifort -shared -o "mylib.so"  ./test.o

Python code is as follows:

from ctypes import *

mylib = CDLL('mylib.so')

ArrayType = c_double*5
IntType = c_int
input1 = ArrayType(1.1,2.2,3.3,4.4,5.5)
input2 = IntType(5)
inputoutput = ArrayType(0,0,0,0,0)              

mylib.mySub.argtypes = [ArrayType,IntType,ArrayType]
mylib.mySub.restype =  ArrayType

output = mylib.mySub(input1,input2,inputoutput)

print '------------------------------------------------------'  
print 'output within Python'
print output
a = [0,1,2,3,4]
for ii in a: print output[ii]

The output gives the following:

#outArray from within Fortran
#1.10000000000000     
#2.20000000000000     
#3.30000000000000     
#4.40000000000000     
#5.50000000000000     
#------------------------------------------------------
#output within Python
#<__main__.c_double_Array_5 object at 0x10aa830>
#2.96439387505e-323
#6.91177308417e-310
#1.48219693752e-323
#6.91177308238e-310
#6.91177319086e-310





Links



Tags