4
請給我一個例子,解釋如何加載&使用Python在C++ dll中調用函數?如何在Python中使用ctypes加載DLL?
我發現一些文章說我們可以使用「ctypes」來使用Python加載和調用DLL中的函數。但我無法找到工作樣本?
如果有人向我提供如何做到這一點,這將是一件好事。
請給我一個例子,解釋如何加載&使用Python在C++ dll中調用函數?如何在Python中使用ctypes加載DLL?
我發現一些文章說我們可以使用「ctypes」來使用Python加載和調用DLL中的函數。但我無法找到工作樣本?
如果有人向我提供如何做到這一點,這將是一件好事。
這裏是一些實際代碼我用在一個項目中加載一個DLL,查找一個函數,並設置和調用該函數。
import ctypes
# Load DLL into memory.
hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")
# Set up prototype and parameters for the desired function call
# in the DLL, `HLLAPI()` (the high-level language API). This
# particular function returns an `int` and takes four `void *`
# arguments.
hllApiProto = ctypes.WINFUNCTYPE (
ctypes.c_int,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p)
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0)
# Actually map the DLL function to a Python name `hllApi`.
hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)
# This is how you can actually call the DLL function. Set up the
# variables to pass in, then call the Python name with them.
p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p ("Z")
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))
在這種情況下的功能是一個在終端模擬器包,這是一個非常簡單的一個 - 它採取四個參數和返回值不(一些經由指針參數實際上返回)。第一個參數(1)表示我們要連接到主機。
第二個參數(「Z」)是會話ID。這個特定的終端模擬器允許通過「Z」的短名稱的「A」。
另外兩個參數只是一個長度,另一個字節的使用目前使我擺脫了困境(我應該記錄下代碼更好一點)。
的步驟是於:
的ctypes的庫具有的所有C數據類型(int
,char
,short
,void*
等),並且可以通過數值或引用傳遞參數。有一個教程位於here。