零终止动态数组作为Python中的返回值

时间:2014-02-11 15:41:47

标签: python ctypes

从python我试图使用c函数返回动态分配的零终止数组的整数:

   
int* my_func(void)
{
    int i;
    int *ret = (int*)malloc((LEN + 1) * sizeof(int));

    for (i = 0; i < LEN; i++) ret[i] = 1;
    ret[LEN] = 0

    return ret;
}

我需要像

这样的东西    
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

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

1 个答案:

答案 0 :(得分:1)

还没有真正使用过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