[英]Pointers and arrays in Python ctypes
我有一個包含 C 函數的 DLL,其原型如下:
int c_read_block(uint32 addr, uint32 *buf, uint32 num);
我想使用 ctypes 從 Python 調用它。 該函數需要一個指向一塊內存的指針,它將把結果寫入其中。 我不知道如何構造和傳遞這么大塊的內存。 ctypes 文檔幫助不大。
構造一個數組並將其傳遞給“byref”,如下所示:
cresult = (c_ulong * num)() err = self.c_read_block(addr, byref(cresult), num)
給出此錯誤消息:
ArgumentError: argument 3: <type 'exceptions.TypeError'>: expected LP_c_ulong instance instead of pointer to c_ulong_Array_2
我猜這是因為 Python ulong 數組與 ac uint32 數組完全不同。 我應該使用create_char_string
? 如果是這樣,我如何說服 Python 將該緩沖區“投射”到 LP_c_ulong?
您可以使用cast
函數進行投射:)
>>> import ctypes
>>> x = (ctypes.c_ulong*5)()
>>> x
<__main__.c_ulong_Array_5 object at 0x00C2DB20>
>>> ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong))
<__main__.LP_c_ulong object at 0x0119FD00>
>>>
您可以轉換結果,但ctypes
允許您直接使用數組代替指針。 問題是代碼中的byref
(相當於指向指針的指針):
所以不是:
cresult = (c_ulong * num)()
err = self.c_read_block(addr, byref(cresult), num)
嘗試:
cresult = (c_ulong * num)()
err = self.c_read_block(addr, cresult, num)
我有一個包含C函數的DLL,其原型如下:
int c_read_block(uint32 addr, uint32 *buf, uint32 num);
我想使用ctypes從Python調用它。 該函數需要一個指向大塊內存的指針,它將結果寫入其中。 我不知道如何構造和傳遞這么大的內存。 ctypes文檔沒有太大幫助。
構造一個數組並將其傳遞給“ byref”,如下所示:
cresult = (c_ulong * num)() err = self.c_read_block(addr, byref(cresult), num)
給出此錯誤信息:
ArgumentError: argument 3: <type 'exceptions.TypeError'>: expected LP_c_ulong instance instead of pointer to c_ulong_Array_2
我猜這是因為Python ulong數組與ac uint32數組完全不同。 我應該使用create_char_string
? 如果是這樣,我該如何說服Python將緩沖區“投射”到LP_c_ulong?
解決方案中有錯字。 為了獲得指向 ulong 數組的指針,您需要轉換為POINTER(list of ulong)
In [33]: ptr = ctypes.cast(x, ctypes.POINTER(ctypes.c_ulong*5))
In [34]: ptr
Out[34]: <__main__.LP_c_ulong_Array_5 at 0x23e2560>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.