我在 C 中有一个函数,它接受一组复杂的 float 并就地对它们进行计算。:
/* foo.c */
void foo(cmplx_float* array, int length) {...}
复杂的 float 结构如下所示:
typedef struct cmplx_float {
float real;
float imag;
} cmplx_float ;
我需要使用 ctypes 在 python 中调用该函数。在 Python 中,我有一个由 complex64 元素组成的 Numpy 一维 ndarray。
我还制作了一个派生自 ctypes.Structure 的类:
class c_float(Structure):
_fields_ = [('real', c_float),
('imag', c_float)]
我想我可能需要另一个实现结构数组的 python 类。总的来说,我只是在将各个部分连接在一起时遇到了问题。需要做些什么才能最终在 Python 中调用我的函数,基本上或多或少是这样的:
some_ctype_array = SomeConversionCode(cmplx_numpy_array)
lib.foo(some_ctype_array, length)
最佳答案
您可以使用 ndpointer
来自 numpy.ctypeslib
将第一个参数声明为 numpy.complex64
类型的一维连续数组:
import numpy as np
from numpy import ctypeslib
# ...code to load the shared library as `lib` not shown...
# Declare the argument types of lib.foo:
lib.foo.argtypes = [ctypeslib.ndpointer(np.complex64, ndim=1, flags='C'), c_int]
然后你可以做,例如,
z = np.array([1+2j, -3+4j, 5.0j], dtype=np.complex64)
lib.foo(z, z.size)
您可能希望将其包装在不需要第二个参数的函数中:
def foo(z):
# Ensure that we use a contiguous array of complex64. If the
# call to foo(z, z.size) modifies z in place, and that is the
# intended effect of the function, then the following line should
# be removed. (The input z is then *required* to be a contiguous
# array of np.complex64.)
z = np.ascontiguousarray(z, dtype=np.complex64)
# Call the C function.
lib.foo(z, z.size)
关于python - 如何使用 ctypes 将 NumPy 复杂数组与 C 函数连接起来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31932781/