gpt4 book ai didi

python - 使用 ctypes 将 malloc 数组从 C 返回到 Python

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:15 25 4
gpt4 key购买 nike

我希望使用一些返回多个未知大小数组的 C 代码。因为有多个数组,我想我需要使用传入的指针,我不确定如何将它与用于设置数组的 malloc 结合使用。

这是一些有代表性的 C 代码:

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>

//gcc -fPIC -shared -o array_test_c.so array_test_c.c

void return_array(int * outdata1v, int * outdata2v) {
int i;
int N = 10;
int * mydatav2, * mydatav3;
mydatav2 = (int *) malloc(sizeof(int) * N);
mydatav3 = (int *) malloc(sizeof(int) * N);
for (i = 0; i<N; i++){
mydatav2[i] = i;
mydatav3[i] = i*2;
}

//this doesn't work which makes sense
outdata1v = mydatav2;
outdata2v = mydatav3;
}

我正尝试通过以下方式将它连接到 Python(这不起作用):

import os
import ctypes


#for c interface
test_module = ctypes.cdll.LoadLibrary(
os.path.join(os.path.dirname(__file__), './array_test_c.so'))

outdata1 = (ctypes.c_int * 0)()
outdata2 = (ctypes.c_int * 0)()
test_module.return_array(outdata1, outdata2)
outdata1 = (ctypes.c_int*10).from_address(ctypes.addressof(outdata1))
print "out", outdata1[-1], outdata1, outdata2

这行不通,我永远无法打印出 20。有什么想法吗?

最佳答案

测试.c

#include <stdlib.h>

#define N 10

void test(int *size, int **out1, int **out2) {
int i;
int *data1, *data2;
data1 = (int *)malloc(sizeof(int) * N);
data2 = (int *)malloc(sizeof(int) * N);
for (i = 0; i < N; i++){
data1[i] = i;
data2[i] = i * 2;
}
*size = N;
*out1 = data1;
*out2 = data2;
}

测试.py

from ctypes import CDLL, POINTER, c_int, byref

dll = CDLL('test.so')

data1 = POINTER(c_int)()
data2 = POINTER(c_int)()
size = c_int()

dll.test(byref(size), byref(data1), byref(data2))

for i in range(size.value):
print i, data1[i], data2[i]

编辑:您应该考虑提供一个函数来释放 malloc 的数据。所以你可以做,例如dll.cleanup(data1, data2)

关于python - 使用 ctypes 将 malloc 数组从 C 返回到 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25409073/

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