Skip to main content
 首页 » 编程设计

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

2025年05月04日9jillzhang

在 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 代码中是未知的,我需要读取数组直到第一个零元素。

请您参考如下方法:

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