[Python] 改寫 Structure 的 __repr__ 函式,顯示 struct 的實際內容

[Python] 改寫 Structure 的 __repr__ 函式,顯示 struct 的實際內容

在用 python 呼叫 C/C++ 的 DLL 時,常常會需要傳遞一個 struct 給 C/C++ 的函式,

struct 在 python 裡可以用 ctypes.Structure 來定義,

例如下面定義了一個 struct,對應到一個裡面有 char*, int, 和 bool 的 C struct:

import ctypes
class TestStruct(ctypes.Structure):
_fields_ = [("pattern", ctypes.c_char_p), ("build", ctypes.c_int), ("load", ctypes.c_bool)]

 

賦值給這個 struct 很簡單,但是在 python 端要查看 struct 裡有什麼東西的話,

一般的 print 只會印出這個 struct 物件的位址,沒啥路用:

>>> s = TestStruct("/tmp/pattern", 1000, True)
>>> print s
<__main__.TestStruct object at 0x10e6fd440>

 

上網查了一下,看到網友提供了很好的解決方法,

那就是覆寫 __repr__() 函式,在裡面把 struct 裡所有的資料 __fields__ 都顯示出來,

舉例來說,我們可以把 __repr__() 寫成像下面這樣:

class TestStruct(ctypes.Structure):
_fields_ = [("pattern", ctypes.c_char_p), ("build", ctypes.c_int), ("load", ctypes.c_bool)]
def __repr__(self): return "%s(%s)" % (self.__class__.__name__, dict((name, getattr(self, name)) for name, _ in self._fields_))

 

這樣的話,print 這個 struct 時,就能將各欄位的值都印出來了,對於除錯很有幫助喔:

>>> s = TestStruct("/tmp/pattern", 1000, True)
>>> print s
TestStruct({'load': True, 'pattern': '/tmp/pattern', 'build': 1000})

 

參考資料:ctypes tricks

 

(本頁面已被瀏覽過 370 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料