admin管理员组文章数量:1566354
使用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程序:
xujijun@pc:~/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)))
运行上述代码,得到输出:
xujijun@pc:~/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__
版权声明:本文标题:python调用c++动态库如何释放_使用ctypes在Python中调用C++动态库 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1725888012a1047246.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论