python ctypes 调用 dll
c++ 编译的 dll,可以被 python ctypes 直接调用
这里讨论一下 Visual Studio 编译的 dll 被 python ctypes 使用的步骤
1. c++ 代码
- vs 要求导出到 dll 的函数必须写上
__declspec(dllexport)
- c++ 会对函数名做 Name Mangling,所以应该用
extern "C"
去除 Mangling extern "C"
必须放在__declspec(dllexport)
前面,不然__declspec(dllexport)
会不生效- 示例代码:
// example.cpp -> example.dll
extern "C"
__declspec( dllexport )
int
triple( int i )
{
return 3 * i;
}
- vs 编译 dll 会带上一个同名的 lib 文件,如果没有 lib,说明 dll 里面一个函数都没有
- 打开同名 lib 可以看到 dll 里面能用的函数名字,例如下图的
triple
- lib 文件看到这个函数名后,python 里就可以用了
2. python 代码
- python 里示例代码
import ctypes
# lib = ctypes.windll.LoadLibrary('example.dll')
# lib = ctypes.cdll.LoadLibrary('example.dll')
lib = ctypes.CDLL('example.dll')
print(lib.triple(3))
3. 常见的问题
- 如果出现
function 'triple' not found
,可以打开 lib 看看是不是没有这个函数 - 如果没写
extern "C"
,函数名会出现 mangling,例如?triple@@YAHH@Z
,这样的函数需要用 ctypes 的 getattr 来找到函数
func = getattr(lib, "?triple@@YAHH@Z")