我在这里有一个关于从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”中所有函数签名的日志,我尝试使用函数的全名,但仍然没有成功。在
任何其他的想法都会被祝福的。在
不幸的是,使用
ctypes
很难以可移植的方式轻松地实现这一点。在ctypes
被设计成在具有与C兼容的数据类型的dll中调用函数。在因为C++没有{{a1},所以你应该知道生成DLL的编译器是如何生成代码的(即类布局…)。在
更好的解决方案是创建一个新的DLL,它使用当前的DLL并将方法包装为纯c函数。有关详细信息,请参见boost.python或SWIG。在
相关问题 更多 >
编程相关推荐