我正在將一個 C 代碼轉換為使用 .dll 檔案的 Python 代碼。 從DLL中訪問命令的語法如下:
cnc_rdmacro(unsigned short FlibHndl, short number, short length, ODBM *macro)。
C代碼 指向odbm資料結構的指標如下:
typedef struct odbm {
short datano ; /* 自定義宏變數編號 */
short dummy ; /* (not使用) */
long mcr_val ; /*自定義宏變數的值 */
short dec_val ; /*小數點的位數 */
} ODBM ;
用于訪問dll命令的C代碼:
short example( short number )
{
ODBM宏。
char strbuf[12] 。
短的ret 。
ret = cnc_rdmacro( h, number, 10, & macro ) 。
我根據上述C語言代碼轉換的Python代碼如下:
import ctypes
fs = ctypes.cdll.LoadLibrary(r" .dll filepath")
ODBM = (ctypes.c_short * 4)() #上述C代碼的資料型別轉換代碼。
ret = fs.cnc_rdmacro(libh, macro_no, 10, ctypes.byref(ODBM) )
在上面的代碼中,我可以得到輸出,沒有任何錯誤。
ODBM的實際資料結構已經宣告了4個資料型別為short、short、long和short的變數,這些變數在C代碼中已經實作。但是我在python中宣告了ODBM的資料結構為ctypes.c_short * 4,即4個短資料型別的變數。
但我的需要是宣告ODBM結構與C代碼中的一樣,并將其傳遞給ctypes.byref()。
最終的解決方案是在一個單一的變數中包含多個資料型別作為ctypes實體。請幫助我。
uj5u.com熱心網友回復:
這里應該使用一個ctypes.Structure:
import ctypes
class ODBM(ctypes.Structure)。
_fields_ = [("datano"/span>, ctypes.c_short),
("dummy", ctypes.c_short) 。
("mcr_val", ctypes.c_long) 。
("Dec_val", ctypes.c_short)]
fs = ctypes.cdll.LoadLibrary(r" .dll filepath")
odbm = ODBM()
ret = fs.cnc_rdmacro(libh, macro_no, 10, ctypes.byref(odbm) )
print(odbm.mcr_val)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329588.html
標籤:
