Python ctypes with Fortran, integer arrays contains unwanted 0s

Viewed 33

I am new to using ctypes and I am trying to pass a integer array from Python into Fortran, however, in doing so, I can see that in Fortran, my passed array contains zeros between every value. Can someone please explain what is going on here?

In my Python program, I am just creating a integer array of dimension 10, and using ctypes I want to pass it into my shared Fortran library:

import ctypes 
import numpy as np

f90 = ctypes.CDLL('./ctypes_test.so')
dim=int(10)
intarr = np.arange(0,dim,dtype=int)
intarr_ = intarr.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
dim_INT = ctypes.c_int(dim)
f90.integerarray_(intarr_, ctypes.byref(dim_INT))

Now my Fortran program will take in the array along with its dimension and initalize it as an integer array of the given dimension. Then I print the array to see what Fortran reads it as:

SUBROUTINE integerarray(arr, dim)
    INTEGER :: arr, dim
    DIMENSION :: arr(dim)
    PRINT*, arr
END

The expected output should be 0, 1, 2, ... 9 as given by the numpy arange function in Python, however I get the following:

0           0           1           0           2           0           3           0           4           0
0

As you can see, there are zeros between every element. What is going on?

1 Answers

I found the solution. It seems like the problem stems from the dtype of the integer array. I found that using dtype=np.int32 which then is assigned to ctypes.c_int works with the Fortran problem. I'm not sure why but it seems like Fortrans INTEGER initialization corrosponds to numpy int32. If anyone wants to expand on why this is the case, please do!

Fixed code:

import ctypes 
import numpy as np

f90 = ctypes.CDLL('./ctypes_test.so')
dim=int(10)
intarr = np.arange(0,dim,dtype=np.int32)
intarr_ = intarr.ctypes.data_as(ctypes.POINTER(ctypes.c_int))
dim_INT = ctypes.c_int(dim)
f90.integerarray_(intarr_, ctypes.byref(dim_INT))

which ultiamtely gives the desired result:

 arr =           0           1           2           3           4           5           6           7           8           9
Related