我有可变数量的 numpy 数组,我想将其传递给 C 函数。我设法传递了每个单独的数组(使用<ndarray>.ctypes.data_as(c_void_p)),但数组的数量可能会有很大差异。
我以为我可以在列表中传递所有这些“指针”并PyList_GetItem()在 C 代码中使用该函数。它就像一个魅力,除了所有元素的值不是我通常在作为函数参数传递时得到的指针。
不过,如果我有:
from numpy import array
from ctypes import py_object
a1 = array([1., 2., 3.8])
a2 = array([222.3, 33.5])
values = [a1, a2]
my_cfunc(py_object(values), c_long(len(values)))
Run Code Online (Sandbox Code Playgroud)
我的 C 代码看起来像:
void my_cfunc(PyObject *values)
{
int i, n;
n = PyObject_Length(values)
for(i = 0; i < n; i++)
{
unsigned long long *pointer;
pointer = (unsigned long long *)(PyList_GetItem(values, i);
printf("value 0 : %f\n", *pointer);
}
}
Run Code Online (Sandbox Code Playgroud)
打印值都是0.0000
我尝试了很多不同的解决方案,使用ctypes.byref()、ctypes.pointer() …