3

我想使用一个在 Python 的 DLL 中定义的函数。从 C++ 函数 (get_version) 返回的值是一个结构

typedef struct myStruct {
    size_t size;
    char * buff;
} myStruct ;

Python代码是:

lib = CDLL(myDLL.dll)
lib.get_version

问题是如何处理返回值?

我已经阅读了 Voo 的答案并阅读了其他帖子,但我仍在为此苦苦挣扎

我声明了结构类(Foo,来自 Voo 的回答)并设置了restype 代码现在看起来

class Foo(Structure):
    _fields_ = [('size', c_size_t), ('buff', c_char_p)]

lib = CDLL(myDLL.dll)
lib.get_version
lib.get_version.restype = Foo._fields_

我收到以下错误 TypeError: restype must be a type, a callable, or None

我读到了这一点,如果我将restypenot 设置为列表,例如:c_char_p,则不会出现错误

当我设置restype

lib.restype = Foo。字段

错误未出现,但restypeforget_version设置不正确在调试中查看变量时:

lib.restype = list: [('size', ), ('buff', )]

lib.get_version.restype = PyCSimpleType:

任何帮助,将不胜感激

4

1 回答 1

2

您必须使用ctypes模块。您只需要使用 ctypes 在您的 python 代码中定义结构。

就像是:

>>> from ctypes import *
>>> class Foo(Structure):
...     _fields_ = [("size", c_size_t), ("buff", c_char_p)]

应该做的伎俩。然后你只需将restype你的get_version方法设置为你的结构,这样解释器就知道它返回了什么,然后你就可以按预期使用它了。

于 2012-06-24T21:31:51.723 回答