python中使用ctypes模块可以在python中直接调用C/C++。 首先要将C/C++编译成动态库(.so),之后python中调用即可
特别注意在调用C++函数需要在函数声明时,加入前缀“ extern “C” ”,这是由于C++支持函数重载功能,在编译时会更改函数名。在函数声明时,前缀extern "C"则确保按C的方式编译。
值得注意的是,一定要有函数输入输出类型的声明,int型不用转换,float和double类型需要进行转换, ctypes中的变量类型与C中对应如下:
ctypes数据类型 C数据类型 c_char char c_short short c_int int c_long long c_float float c_double double c_void_p void c_uint8 unsigned char
这里如果c/c++的.so动态库的接口形参的类型python不存在则会报段错误!!
例如:
动态库接口为 string Example(string filePath );
python代码:
import ctypes from ctypes import * def convert_type(input): ctypes_map = {int:ctypes.c_int, float:ctypes.c_double, str: