【问题标题】:tried to get an array from a C func in Python3试图从 Python3 中的 C 函数获取数组
【发布时间】:2019-07-08 04:13:42
【问题描述】:

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

系统为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。

【问题讨论】:

    标签: python c python-3.x


    【解决方案1】:

    您在属性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)
    

    【讨论】:

    • @SovLynE 如果答案解决了您的问题,您可以通过单击投票按钮下方的勾号将其标记为已回答。
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多