[英]Handling struct returned from c++ called from python
我想使用Python中的DLL中定義的函數。 從C ++函數(get_version)返回的值是一個結構
typedef struct myStruct {
size_t size;
char * buff;
} myStruct ;
Python代碼是:
lib = CDLL(myDLL.dll)
lib.get_version
問題是如何處理返回值?
我已經讀過Voo的答案並閱讀其他帖子,但我仍然在努力解決這個問題
我聲明了struct類(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必須是類型,可調用或無
我讀到了這個,如果我將restype
設置為不是列表,例如:c_char_p,則不會出現錯誤
當我設置restype
lib.restype = Foo。 領域
錯誤沒有出現,但get_version
的restype
未正確設置在查看debug中的變量時:
lib.restype = list:[('size',),('buff',)]
lib.get_version.restype = PyCSimpleType:
任何幫助,將不勝感激
你必須使用ctypes模塊。 您只需要使用ctypes在python代碼中定義結構。
就像是:
>>> from ctypes import *
>>> class Foo(Structure):
... _fields_ = [("size", c_size_t), ("buff", c_char_p)]
應該做的伎倆。 然后你只需設置restype
您的get_version
方法,你的結構,這樣的解釋知道它不會返回,然后你可以使用它作為預期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.