python - 返回指向具有 ctypes 的结构的指针的函数

标签 python ctypes

我的C函数原型(prototype)是:

typedef struct {
    int a; 
    int b;
} foo_t;

foo_t* foo(int a);

在 Python 中我必须重新定义我的结构:

class Foo(Structure):
    _fields_ = [("a", c_int), ("b", c_int)]

我的问题是如何在 Foo 中正确地转换我的返回值?

>>> dll.foo.restype = POINTER(Foo)
>>> ret = dll.foo(42);
>>> print ret
<dll.LP_Foo object at 0xffe7c98c>
>>> print ret.a
AttributeError: 'LP_Foo' object has no attribute 'a'

我也尝试过 Foo 而不是 POINTER(Foo)。有了这个,我可以访问 Foo 成员,但值是错误的。

来自 ctypes我可以读到这个:

ctypes.POINTER(type) This factory function creates and returns a new ctypes pointer type. Pointer types are cached an reused internally, so calling this function repeatedly is cheap. type must be a ctypes type

所以类型不能是Foo。我可能必须找到另一种方法。

最佳答案

来自文档:

Pointer instances have a contents attribute which returns the object to which the pointer points

所以尝试:

>>> print ret.contents.a

请注意文档说明:

Note that ctypes does not have OOR (original object return), it constructs a new, equivalent object each time you retrieve an attribute

关于python - 返回指向具有 ctypes 的结构的指针的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32370917/

相关文章:

python - 调整(缩小)ctypes 数组的大小

Python/PyGame 从类/方法创建具有随机属性的随机怪物

python - 关于Python中的序列类型

c++ - ctypes 类成员访问段错误

python - 带有函数和结构指针的 ctypes 中的错误

加载库时Python ctypes错误GOMP_ritic_end

python - 从 Python 脚本运行 ImageJ 宏错误未找到

python - 作为文件夹中的音乐文件,将它们从 .ogg 转换为 .mp3 (python)

Python-将值附加到列表列表中的每个子列表

python - 使用 Python ctypes 访问 Visual Foxpro COM DLL