python调用c++动态库 类_使用ctypes在Python中调用C++动态库

使用ctypes在Python中调用C++动态库

入门操作

使用ctypes库可以直接调用C语言编写的动态库,而如果是调用C++编写的动态库,需要使用extern关键字对动态库的函数进行声明:

#include

using namespace std;

extern "C" {

void greet() {

cout << "hello python" << endl;

}

}

将上述的C++程序编译成动态链接库:

g++ hello.cpp -fPIC -shared -o hello.so

在Python代码中使用ctypes导入动态库,调用函数:

# -*- coding: utf-8 -*- #

from ctypes import CDLL

hello = CDLL('./hello.so')

if __name__ == '__main__':

hello.greet()

运行上述Python程序:

[email protected]:~/codespace/python$ python3 hello.py

hello python

参数传递

编写一个整数加法函数

#include

using namespace std;

extern "C" {

int add(int a, int b) {

return a + b;

}

}

编译得到动态库,在Python代码中调用:

# -*- coding: utf-8 -*- #

from ctypes import CDLL

hello = CDLL('./hello.so')

if __name__ == '__main__':

a = input('input num1: ')

b = input('input num2: ')

print('output: %d' % hello.add(int(a), int(b)))

运行上述代码,得到输出:

[email protected]:~/codespace/python$ python3 hello.py

input num1: 12

input num2: 34

output: 46

尝试传递字符串参数

#include

#include

using namespace std;

extern "C" {

void print_name(const char* name) {

printf("%s\n", name);

}

}

Python代码调用:

# -*- coding: utf-8 -*- #

from ctypes import CDLL

hello = CDLL('./hello.so')

if __name__ == '__main__':

nam

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值