python - 如何使用 ctypes 将 NumPy 复杂数组与 C 函数连接起来?

标签 python c numpy ctypes

我在 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/

相关文章:

python - '值错误: could not convert string to float' in python sklearn

c - 防止缓冲区溢出

c - 识别 shell 命令文本中未加引号的特殊字符

c - C中静态函数的正确用法是什么?

python - 如何根据 python 中提供的 0 和 1 矩阵生成矩阵组合?

python - 如何在 matplotlib 中使用 xy 数据设置 quiverkey 长度缩放?

python - 我怎样才能通过一个函数保存我的参数值,以便它可以使用它的初始值多次使用?

python - 使用 Python Pandas 的 Excel 'COUNTIF() ' 功能

Python 2.7 尝试使用范围和重复来缩小列表范围

python - 为什么 where 参数默认值为 false?