gpt4 book ai didi

Python 使用 ctypes 自定义结构调用 C 共享库

转载 作者:太空狗 更新时间:2023-10-29 22:23:24 24 4
gpt4 key购买 nike

我在 Linux 系统上从 Python 调用 C 共享库。

我遇到的问题是 C 库中的函数将指向结构的指针作为参数。然后它为结构数组分配内存,用数据填充数组并返回。所以我将函数定义为

from ctypes import *
class myStruct(Structure):
_fields_ = [("id", c_uint), "name", c_char*256)]

library.func.argtypes = [POINTER(myStruct)]

然后我这样调用它:

Myfoo = myStruct
Foo = pointer(Myfoo)
Bar = library.func(Foo)
for i in range(Bar):
print("id = %u, name = %s" % (Foo[i].id, Foo[i].name))

Bar 包含由 func 分配的结构数。

无论我做什么,我都无法从 Foo 中获取任何数据。几个月来,我已经尝试了多种不同的变体。我可以查看 C 库中的日志,我知道它正在获取数据并返回它,但我似乎找不到从 Python 中提取它的方法。

有什么想法吗?

最佳答案

如果我从您对问题的评论中得到了“func”原型(prototype),那么应该这样做:

C代码

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

struct Foo
{
unsigned int id;
char name[256];
};

__declspec(dllexport) int func(struct Foo **ppFoo)
{
int i;
struct Foo *foo = malloc(5 * sizeof(struct Foo));
for(i=0;i<5;i++)
{
foo[i].id = i;
sprintf_s(foo[i].name,_countof(foo[i].name),"Name#%d",i);
}
*ppFoo = foo;
return 5;
}

Python代码

from ctypes import *
dll = CDLL('x')
class Foo(Structure):
_fields_ = [
('id',c_uint),
('name',c_char*256)]

pfoo = POINTER(Foo)()
count = dll.func(byref(pfoo))
for i in xrange(count):
print pfoo[i].id,pfoo[i].name

输出

0 Name#0
1 Name#1
2 Name#2
3 Name#3
4 Name#4

请注意,您仍然需要以某种方式释放分配的内存...

关于Python 使用 ctypes 自定义结构调用 C 共享库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10668645/

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