使用C++而不是C来编写so库时每每会遇到一些问题,这里着重探讨一下linux环境下C++编写so库python
及python调用so库须要注意的地方。linux
test.ccios
#include<iostream> extern "C"{ // 重要,由于使用g++编译时函数名会改变,比方print_msg(const char*) // 会编译成函数名 print_msg_char,这会致使python调用这个函数的时候 // 找不到对应的函数名,这有加了 extern "C",才会以C语言的方式进行 // 编译,这样不会改变函数名字 void print_msg(const char* s) { std::cout<<s<<std::endl; } int add_Integer(int a,int b) { return a+b; } }
编译命令:函数
g++ -shared test.cc -o test.so -fPICcode
-fPIC 的参数不能丢,PIC(Position Independent Code)表示生成代码与位置无关,这样才能ip
达到动态连接的目的。utf-8
script.pyget
#! /usr/bin/env/python # _*_ encoding : utf-8 _*_ from ctypes import * import os sotest = cdll.LoadLibrary(os.getcwd()+ "/test.so") sotest.print_msg("hello,my shared object used by python!") print("4+5=%s" %sotest.add_Integer(4,5))