Python ctypes与Fortran,整数数组包含不需要的0



我是ctypes的新手,我正试图将一个整数数组从Python传递到Fortran中,但是,在这样做的过程中,我可以看到在Fortran中,我传递的数组在每个值之间都包含零。有人能解释一下这里发生了什么吗?

在我的Python程序中,我只是创建了一个维度为10的整数数组,并使用ctypes将其传递到我的共享Fortran库:

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))

现在,我的Fortran程序将接收数组及其维度,并将其初始化为给定维度的整数数组。然后我打印数组以查看Fortran将其读取为:

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

预期输出应为0、1、2。。。9,正如Python中的numpy arange函数所给出的,然而我得到了以下内容:

0           0           1           0           2           0           3           0           4           0
0

正如你所看到的,每个元素之间都有零。发生了什么事?

我找到了解决方案。问题似乎源于整数数组的数据类型。我发现使用dtype=np.int32(然后将其分配给ctypes.c_int(可以解决Fortran问题。我不知道为什么,但Fortrans INTEGER的初始化似乎将指针更正为numpy int32。如果有人想进一步解释为什么会出现这种情况,请这样做!

固定代码:

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))

它多次给出所需的结果:

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

最新更新