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__

本文标签: 动态Pythonctypes