gpt4 book ai didi

python - 使用 Python 从 C/C++ DLL 调用方法

转载 作者:行者123 更新时间:2023-11-30 16:58:16 26 4
gpt4 key购买 nike

我这里有一个关于从 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)
>>>

这个示例在函数是外部时有效,但是,假设我有一个对象的引用,并且我想使用参数从该对象调用函数,我该怎么做?

我确实看到了“dumpbin -exports”中所有函数签名的日志,并且我尝试使用该函数的全名,但仍然不起作用。

任何其他想法都会受到祝福。

最佳答案

不幸的是,您无法使用 ctypes 轻松且可移植地做到这一点。

ctypes 旨在调用 DLL 中具有C 兼容数据类型的函数

因为没有standard binary interface对于C++,您应该知道生成DLL的编译器如何生成代码(即类布局...)。

更好的解决方案是创建一个新的 DLL,它使用当前的 DLL 并将方法包装为纯 C 函数。请参阅boost.pythonSWIG了解更多详情。

关于python - 使用 Python 从 C/C++ DLL 调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38997898/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com