Python中以零结尾的动态数组作为返回值

Python中以零结尾的动态数组作为返回值,python,ctypes,Python,Ctypes,在python中,我尝试使用c函数返回动态分配的以零结尾的整数数组: int*my_func(无效) { int i; int*ret=(int*)malloc((LEN+1)*sizeof(int)); 对于(i=0;i

在python中,我尝试使用c函数返回动态分配的以零结尾的整数数组:

int*my_func(无效)
{
int i;
int*ret=(int*)malloc((LEN+1)*sizeof(int));
对于(i=0;i
我需要像这样的东西

from ctypes import *

l = cdll.LoadLibrary("lib.so")
my_func = l.my_func
my_func.restype = c_int * LEN

for x in my_func(): print x

问题是python代码中不知道
LEN
,我需要读取数组直到第一个零元素。

还没有真正使用ctypes,但是:

from ctypes import *

l = cdll.LoadLibrary("lib.so")
my_func = l.my_func
my_func.restype = POINTER(c_int)

i = 0;
rv = my_func()
while rv[i]:
    print rv[i]
    i += 1

ctypes允许您将
restype
设置为数组,但它并没有按照您的想法执行。它将返回的指针存储为数组的第一项。例如,在许多情况下,
c类型
与您无论如何都无法更改的库一起使用。让OP决定什么是合理的……如果需要数组,请使用
rv_array=cast(rv,指针(c_int*i))[0]
。您可以将
my_func
的属性设置为返回数组的函数。