编写好cpp文件如下:
#include <stdio.h> #include<stdlib.h> #include<string.h> extern "C" { char* itype(int b) { char* s = (char*)malloc(100 ); sprintf(s,"%d",b); return s; } char* ftype(float b) { char* s = (char*)malloc(100 ); sprintf(s,"%f",b); return s; } char* stype(char* b) { char* s = (char*)malloc(100 ); if (s) strcpy ( s , b ); return s; } }
1 若采用g++ -c -shared -fPIC s.cpp -o liba.so编译会出现only ET_DYN and ET_EXEC can be loaded错误;
2若cpp中不声明extern "C" 则会出现AttributeError: ./s.so: undefined symbol: ftype错误;
完整编译好后生成liba.so
然后在Python中调用动态库liba.so
Python代码
# coding=gbk import ctypes as ct import time if __name__ == '__main__': a = "fds" a = ct.c_char_p("ds") dll = ct.cdll.LoadLibrary("./liba.so") b = 2.5 time_begin = time.clock() if type(b)==float: b=ct.c_float(b) for i in range(50000): p=dll.ftype(a, b) elif type(b)==unicode: b=b.encode('GB18030') elif type(b)==int: for i in range(50000): p=dll.itype(a, b) elif type(b)==str: b=ct.c_char_p(b) for i in range(50000): p=dll.stype(a, b) t = time.clock() - time_begin print("\nUse time: %s" %t)python代码中特别要注意传入参数的类型和调用动态库后返回值的类型要经过ctype转换。
至此,Python调用c扩展完毕。