Python ctypes的数组输出

array output from Python ctypes?

本文关键字:输出 数组 ctypes Python      更新时间:2023-10-16

我需要使用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"

我最初并不认为这会适用于动态大小的数组,但我所要做的就是在每次调用之前重新定义参数类型。