[英]Calling the C++ function in python using ctypes
我有 C++ 代碼,其中有一個 function 需要三個 arguments
HRESULT WINAPIV GIDItem (Address* pa, LPWSTR cmdvalue, LPWSTR* string_value)
我能夠在 Ctypes 中加載 dll
import ctypes
uDl = ctypes.CDLL(r"test1")
uDl_function=uDl.CAIA # we are creating function pointer
pa=uDl_function('something')
uD = ctypes.CDLL(r"test.dll")
uD_function =uD.GIDItem # we are creating function pointer
string_value= ctypes.c_wchar_p()
cmdvalue=ctypes.c_wchar_p("CM")
dI=uD_function(ctypes.POINTER(pa),cmdvalue,ctypes.byref(string_value))
我得到以下錯誤,
dI=uD_function(ctypes.POINTER(pa),cmdvalue,ctypes.byref(string_value))
TypeError: must be a ctypes type
我只是在看一些關於 DLL 的文章,在 C++ 中,Dll 被稱為如下
fpGIDItem (pA, L"CMD", &cD)
當您查看上面的代碼時,“CMD”是cmdvalue
,字符串值與&cD
一起發送
請幫我解決這個問題
ctypes.POINTER(pa)
是一種類型而不是實例,這就是它給出您看到的錯誤的原因。
如果您創建一個在 C 中使用的工作示例,則更容易確定如何在 Python 中編寫它,但我會嘗試一下。
正確設置.argtypes
上的 .argtypes 和restype
,以便ctypes
為您進行類型檢查。
像下面這樣的東西應該可以工作。
from ctypes import *
dll = CDLL(r'test1')
dll.CAIA.argtypes = c_wchar_p,
dll.CAIA.restype = c_void_p # generic void* should work.
dll2 = ctypes.CDLL(r'test.dll')
dll2.GIDItem.argtypes = c_void_p,c_wchar_p,POINTER(c_wchar_p)
dll2.GIDItem.restype = c_long
pa = dll.CAIA('something')
string_value = c_wchar_p()
result = dll2.GIDItem(pa,'CM',byref(string_value))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.