简体   繁体   中英

Calling methods from C/C++ DLL with Python

I do have a tutorial here about calling functions from ac/c++ dll, the example is written here from the 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)
>>>

This example works when the function is external, however, let's assume I have a reference to an object, and I want to call a function from that object with params, how do I do that?

I did saw the log of all function signatures from 'dumpbin -exports', and I tried using the full name of the function, and still it didn't work.

Any other ideas would be blessed.

Unfortunately, you can not do that easily and in portable way with ctypes .

ctypes is designed to call functions in DLLs with C compatible data types.

Since there is no standard binary interface for C++, you should know how the compiler which generates the DLL, generates the code (ie class layout ... ).

A better solution is to create a new DLL which uses the current DLL and wraps the methods as plain c functions. See boost.python or SWIG for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM