我这里有一个关于从c / c ++ dll调用函数的教程,这个例子是从official tutorial写的。
WINUSERAPI int WINAPI
MessageBoxA(
HWND hWnd,
LPCSTR lpText,
LPCSTR lpCaption,
UINT uType);
Here is the wrapping with ctypes:
>>>
>>> from ctypes import c_int, WINFUNCTYPE, windll
>>> from ctypes.wintypes import HWND, LPCSTR, UINT
>>> prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
>>> paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
>>> MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)
>>>
The MessageBox foreign function can now be called in these ways:
>>>
>>> MessageBox()
>>> MessageBox(text="Spam, spam, spam")
>>> MessageBox(flags=2, text="foo bar")
>>>
A second example demonstrates output parameters. The win32 GetWindowRect function retrieves the dimensions of a specified window by copying them into RECT structure that the caller has to supply. Here is the C declaration:
WINUSERAPI BOOL WINAPI
GetWindowRect(
HWND hWnd,
LPRECT lpRect);
Here is the wrapping with ctypes:
>>>
>>> from ctypes import POINTER, WINFUNCTYPE, windll, WinError
>>> from ctypes.wintypes import BOOL, HWND, RECT
>>> prototype = WINFUNCTYPE(BOOL, HWND, POINTER(RECT))
>>> paramflags = (1, "hwnd"), (2, "lprect")
>>> GetWindowRect = prototype(("GetWindowRect", windll.user32), paramflags)
>>>
这个例子在函数是外部时有用,但是,假设我有一个对象的引用,我想用params从该对象调用一个函数,我该怎么做?
我确实看到了'dumpbin -exports'中所有函数签名的日志,我尝试使用函数的全名,但它仍无法正常工作。
任何其他想法都会受到祝福。
答案 0 :(得分:0)
不幸的是,您无法使用ctypes
以便携方式轻松完成此操作。
ctypes
旨在使用 C兼容数据类型在DLL中调用函数。
由于C ++没有standard binary interface,你应该知道生成DLL的编译器如何生成代码(即类布局......)。
更好的解决方案是创建一个新的DLL,它使用当前的DLL并将方法包装为普通的c函数。有关详细信息,请参阅boost.python或SWIG。