gpt4 book ai didi

python - 尝试从Python3中的C函数获取数组

转载 作者:行者123 更新时间:2023-11-30 14:37:57 25 4
gpt4 key购买 nike

我尝试使用 ctypes 从 Python3 中的 C 函数获取数组,失败了。

系统为macOS Mojave 10.14.5。Python3版本为3.7.3。

这是 C 代码:

#include "stdlib.h"

#include "stdio.h"

int* func(int num){

int *result = (int *)malloc(num*sizeof(int)), i=num ;
while (i-->0){
result[i] = num-i;
printf("%d:%d\n",i, num-i);
}
return result;
}

这是 Python3 代码: 从 ctypes 导入 *

dll = CDLL('./test.so')
func = dll.func
func.argtypes = [c_int]
func.restypes = POINTER(c_int*12)
res = func(12)#Here res is an int
res = cast(res, POINTER(c_int*12)).contents
for i in res:
print(i)#Segmentation fault: 11

除了结果可以转换为 numpy.ndarray 之外。

最佳答案

属性 func.restypes 中有拼写错误。它应该被称为 func.restype (参见文档 here )。更改属性可以消除段错误并正确打印数组。

这也使得转换变得多余,您可以直接迭代内容,如下所示:

func = dll.func
func.argtypes = [c_int]
func.restype = POINTER(c_int*12)
res = func(12)
for i in res.contents:
print(i)

关于python - 尝试从Python3中的C函数获取数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56928347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com