五.在python环境中调用C/C++代码
前面是两点基础,这节说明在python环境中调用C/C++代码。
大致有两种方式:
1. 将c/c++代码编译成(操作系统)标准的动态库,在python中“引用”后调用
2. 将c/c++代码写成python扩展库,就如同python的内置的标准库一样,正常引用后调用
第一种方式比较简单,下面是一个简单示例。
C/C++代码(文件名为mm.cpp)
#include <stdio.h>
#ifdef __cplusplus
extern "C"
#endif
void myconcate(char *dest, char *src, int i, double f)
{
sprintf(dest, "string:%s, integer:%d, float:%f", src, i, f);
}
注意,C++代码必须在函数前加 extern “C”。编译成动态库libmm.so
gcc mm.cpp -fPIC - shared -o libmm.so
Python代码
import ctypes
mm=ctypes.CDLL("./libmm.so")
dest=ctypes.create_string_buffer(200)
mm.myconcate(dest,b"This",100,ctypes.c_double(12.3))
print(repr(dest.r