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")
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值