我想做的是将 C 函数转换为 python 函数。
例如,我有一个预先定义的 C 函数原型(prototype):
function_test(ViInt32 Arraysize, ViReal64 readingArray[], ViInt32 *Actual_rraysize)
上述函数的输入是Arraysize
,它是readingArray
参数中的元素数量。
上述函数的输出是readingArray[]
和Arraysize
。 readingArray[]
返回结果数组,Actual_arraysize
表示返回数组的实际大小。
下面是我使用这个 C 函数原型(prototype)编写的 Python 函数:
from ctypes import *
def Py_function_test(self, arraysize, readingarray = [], actualarraysize = [-1e-10]):
while len(readingarray) < arraysize:
readingarray.append(0)
_c_actualarraysize = c_int()
ArrayOfDouble = c_double * arraysize
_c_readingarray = ArrayOfDouble()
self.function_test(c_int(arraysize),
byref(_c_readingarray),
byref(_actualarraysize))
for n in range(arraysize):
readingarray[n] = _c_readingarray[n]
actualarraysize[0] = _c_actualarraysize.value
最后发现acutalarraysize
的值修改成功。但调用c函数原型(prototype)
后,readingarray
的值没有改变。
这种情况该如何处理,是不是因为我不应该使用byref
?
最佳答案
是的,传递数组时不需要byref。并且使用列表作为默认参数值会导致意外的错误。您可以在 Python 函数中返回数组和实际数组大小。
这是我的代码:
from ctypes import *
test = cdll.LoadLibrary("test")
test.function_test.argtypes = [
c_int, POINTER(c_double), POINTER(c_int)
]
def Py_function_test(arraysize):
_c_readingarray = (c_double*arraysize)()
_c_actualarraysize = c_int()
test.function_test(arraysize, _c_readingarray, byref(_c_actualarraysize))
return _c_readingarray, _c_actualarraysize.value
array, size = Py_function_test(10)
print list(array), size
C 代码:
void function_test(int Arraysize, double readingArray[], int *Actual_rraysize)
{
int i;
*Actual_rraysize = Arraysize/2;
for(i=0;i<*Actual_rraysize;i++)
readingArray[i] = i;
}
Python代码的输出是:
[0.0, 1.0, 2.0, 3.0, 4.0, 0.0, 0.0, 0.0, 0.0, 0.0] 5
关于python - 调用函数时如何在 ctyps 中返回数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11533971/