[英]Reading double c structures of Dll with Ctypes in Python
我對這個問題做了很多研究..但是沒有地方,我找不到它。 我試圖通過調用 c dll 來調用雙 c 結構。
我的問題是,我在 python 中聲明“類結構”的方法正確嗎? 我無法認為我就在路上。 因為即使我想從 dll 調用的函數,它也沒有輸出任何東西。
[Visual C++/C]
我確實嘗試過 C 語法代碼,
typedef sturct {
int nBoardNum;
struct{
char pBoardName[16];
int nBoardID;
}BOARDINDEX[8];
}AAPBOARDINFO, *PAAPBOARDINFO;
HANDLE AcapOpen(char* cpBoardName, int nBoardNo, int nCh)
[Python]
我像這樣更改了 Python 語法。
import ctypes as c
class BOARDINDEX(c.Structure):
_field_ = [("nBoardName", c.c_char_p * 16),("nBoardID", c.c_int)]
class AAPBOARDINFO(c.Structure):
_field_ = [("nBoardNum", c.c_int), ("BOARDINDEX", BOARDINDEX * 8)]
AapLib2 = c.WinDLL("AapLib2.dll")
BoardName = ["ABC","FWD","HGW"]
BoardNo = 0
ch = 1
output = Open(BoardName, BoardNo, ch)
def Open(BoardName, BoardNo, ch)
func = AapLib2.AcapOpen
func.argtypes = [c.POINTER(BOARDINDEX),c.c_int, c.c_int]
func.restype = c.c_int
ref = BOARDINDEX()
res = func(c.byref(ref.nBoardName),BoardNo, ch)
return res
調用 Open() 函數時沒有任何結果......
請考慮我的要求,任何答案都會很棒...
你需要知道的一切,都可以在[Python 3.Docs]: ctypes - A external function library for Python 中找到。
代碼有幾個問題:
char pBoardName[16]
映射到ctypes.c_char * 16
(不是c_char_p )wintypes.HANDLE
。 這種不匹配可以(並且很可能會)產生:
這是您的代碼的修改版本。 不用說,我實際上並沒有測試它,因為我沒有.dll :
#!/usr/bin/env python3
import sys
import ctypes
from ctypes import wintypes
class BOARDINDEX(ctypes.Structure):
_fields_ = [
("nBoardName", ctypes.c_char * 16),
("nBoardID", ctypes.c_int),
]
class AAPBOARDINFO(ctypes.Structure):
_fields_ = [
("nBoardNum", ctypes.c_int),
("BOARDINDEX", BOARDINDEX * 8),
]
def open_board(board_name, board_no, ch):
AcapOpen = aaplib2.AcapOpen
AcapOpen.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_int]
AcapOpen.restype = wintypes.HANDLE
ref = BOARDINDEX(board_name, board_no) # Probably this line should be replaced by the 3 (commented) ones below (AcapGetBoardInfo prototype would have to be specified as well)
#abi = AAPBOARDINFO()
#AcapGetBoardInfo(ctypes.byref(abi))
#ref = abi.BOARDINDEX[0]
res = AcapOpen(ref.nBoardName, ref.nBoardID, ch)
return res
def main():
board_names = ["ABC", "FWD", "HGW"]
board_no = 0
ch = 1
aaplib2 = ctypes.WinDLL("AapLib2.dll")
output = open_board(board_names[0], board_no, ch)
print(output)
if __name__ == "__main__":
print("Python {0:s} {1:d}bit on {2:s}\n".format(" ".join(item.strip() for item in sys.version.split("\n")), 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
main()
print("\nDone.")
讓我知道這對你有什么影響。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.