- 前言
- 一、类型转换
- 二、使用步骤
- 1.将C/C++编译成so库文件
- 2.代码示例
- 总结
前言
python调用C/C++代码,我们只是简单调用,因为需要利用C语言中内存动态分配,如果需要在python中使用C++类这种复杂项目,建议使用Boost.python库。这里将C/C++代码编译成so库文件,然后python引用Ctypes库,但是python、C/C++、Ctypes库类型转换需要注意。
一、类型转换
C类型 Python类型 ctypes 类型 char 1-character/string c_char wchar_t 1-character/Unicode、string c_wchar char int/long c_byte char int/long c_ubyte short int/long c_short unsigned short int/long c_ushort int int/long C_int unsigned int int/long c_uint long int/long c_long unsigned long int/long c_ulong long long int/long c_longlong unsigned long long int/long c_ulonglong float float c_float double float c_double char *(NULL terminated) string or none c_char_p wchar_t *(NULL terminated) unicode or none c_wchar_p void * int/long or none c_void_p二、使用步骤 1.将C/C++编译成so库文件
利用gcc将需要调用的C/C++模块编译成so库文件:
g++ -o test.so -shared -fPIC main.cpp2.代码示例
C/C++:C++代码需要extern C才可进行后续编库,C语言不需要
#include#include "FileOp.h" extern "C"{ const char* readFileByBlock(uint a, const char *filename){ char *c= strdup(readFileBlock(a,filename).c_str()); return c; } void writeFileByAddr(uint addr,const char *data,const char *filename){ string d=data; writeFileByAddr(addr,d,filename); cout<<"write file by addr success!"< string d=data; int newaddr=writeFileByNewAddr(d,filename); cout<<"write file by newaddr success!"< string a=readFileBlock(4092,"data_file"); cout< python:
import ctypes ll= ctypes.cdll.LoadLibrary lib=ll("./test.so") # all=lib.main() # print all lib.readFileByBlock.restype = ctypes.c_char_p lib.readFileByBlock.argtypes = [ctypes.c_int,ctypes.c_char_p] lib.writeFileByAddr.argtypes = [ctypes.c_int,ctypes.c_char_p,ctypes.c_char_p] lib.writeFileByNew.argtypes = [ctypes.c_char_p,ctypes.c_char_p] lib.writeFileByNew.restype = ctypes.c_int file=ctypes.c_char_p(bytes("./cmake-build-debug/data_file")) sec=lib.readFileByBlock(0,file)[:-1].split(",") print (sec) list=[] for i in range(0,12): list.append('0') str=ctypes.c_char_p(bytes(list)) lib.writeFileByAddr(0,str,file) sec=lib.readFileByBlock(0,file)[:-1].split(",") print (sec) # str=ctypes.c_char_p(bytes("123,1241,23423,345,5675,567,567,896,23,234,2342")) new=lib.writeFileByNew(str,file) print(new) print ("finish")
总结以上就是简单的python调C/C++代码,注意类型转换也就是返回参数以及传入参数的类型。



