Python ctypes的数组输出
array output from Python ctypes?
我需要使用ctypes从Python调用一个C函数,并让该函数向Python提供一个或多个数组。数组将始终是简单的类型,如long、bool、double。
我更喜欢数组可以动态调整大小。每次通话前我都会知道需要什么,但不同的通话应该使用不同的尺寸。
我想我应该在Python中分配数组,并让C代码覆盖内容,这样Python最终可以取消分配它分配的内存。
我同时控制Python和C代码。
我现在有这个不起作用:
C:
FOO_API long Foo(long* batch, long bufferSize)
{
for (size_t i = 0; i < bufferSize; i++)
{
batch[i] = i;
}
return 0;
}
Python:
print "start test"
FooFunction = Bar.LoadedDll.Foo
longPtrType = ctypes.POINTER(ctypes.c_long)
FooFunction.argtypes = [longPtrType, ctypes.c_long]
FooFunction.restype = ctypes.c_long
arrayType = ctypes.c_long * 7
pyArray = [1] * 7
print pyArray
errorCode = FooFunction(arrayType(*pyArray), 7)
print pyArray
print "test finished"
产品:
start test
[1, 1, 1, 1, 1, 1, 1]
[1, 1, 1, 1, 1, 1, 1]
test finished
应生产:
start test
[1, 1, 1, 1, 1, 1, 1]
[0, 1, 2, 3, 4, 5, 6]
test finished
为什么这不起作用?还是我需要用不同的方式来做这件事?
C数组是使用python列表构建的;两者都是不同的对象。并且代码是打印python列表,该列表不受Foo
调用的影响。
您需要构建C数组,传递它,然后在调用后使用它:
arrayType = ctypes.c_long * 7
array = arrayType(*[1] * 7)
print list(array)
errorCode = FooFunction(array, len(array))
print list(array)
感谢falstru提供了极其快速的答案。我没有马上注意到,同时我也意识到了这一点,这似乎也很有效。我想知道一个是否比另一个更可取?
print "start test"
FooFunction = GpGlobals.LoadedDll.Foo
longArrayType = ctypes.c_long * (7)
FooFunction.argtypes = [longArrayType, ctypes.c_long]
FooFunction.restype = ctypes.c_long
pyArray = longArrayType()
for l in pyArray:
print l
errorCode = FooFunction(pyArray, 7)
for l in pyArray:
print l
print "test finished"
我最初并不认为这会适用于动态大小的数组,但我所要做的就是在每次调用之前重新定义参数类型。
相关文章:
- 使用递归输出数组
- C++ 输出数组中的最高元素
- 空指针(为缺少的输出数组调用的 create() 在 create,文件 /home/m/OpenCV/modules/
- C++ 为什么我会得到垃圾输出数组?
- C 默认如何输出数组
- 使用递归输出数组
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 递归函数,用于输出数组的最小数量
- 如何在 c++ 中水平输出数组
- 冒泡排序未正确排序或输出数组值
- 按相反顺序输出数组的元素
- 制作一个排列函数,输出数组中所有可能的排列
- OpenCV (c++)缝合器不写入输出数组
- 创建一个3x3x3阵列.用0到9之间的随机值填充.输出数组.找出3个最小值和3个最大值的输出
- 实现[B,C]=f(A)语法(函数f作用于具有两个或多个输出数组的数组)
- 双指针输出数组参数异常
- SWIG Python C++输出数组给出'unknown type'错误
- 以 XLL 为单位获取调用方定义的输出数组尺寸
- c++:如何从函数接收可变长度的输出数组
- 未定义的符号 输出数组 opencv fedora.