首页 > g++编译加入-fPIC -shared参数后调用PyRun_SampleString段错误

g++编译加入-fPIC -shared参数后调用PyRun_SampleString段错误

为了实现抓包功能,用c++写了个so库供python调用,编译命令为
g++ -o sniff.so -fPIC -shared sniff.cpp -lsqlite3 -lpcap -I/usr/include/python2.7 -L/usr/lib/python2.7 -lpython2.7
但是发现加入-fPIC -shared参数后所有Python.h中的函数,如PyRunSampleString等执行的时候都会出现段错误。
用以下例子做示范:

//abc.py C++调用这个模块
print "hello"
//a.cpp 编译为可供调用的库
#include <Python.h>
#include "string"
#include "iostream"
#include <stdio.h>
using namespace std;


int main(){
    cout<<"going init python\n";
    Py_Initialize();
    cout<<"init python success\n";
    if (!Py_IsInitialized() ){
        cerr<<"Python init failed!"<<endl;
        return -1;
    }
    PyObject *moduleName,*pModule,*pClass,*pEvent,*pFire,*pArgs;
    cout<<"python init success!\n";
    PyRun_SimpleString("import sys");
    cout<<"import sys\n";
    PyRun_SimpleString("sys.path.append('./')");
    cout<<"sys path append\n";
    pModule = PyImport_ImportModule("abc");
    if(!pModule){
        cerr<<"sniff.so:can not load events.py"<<endl;
        return -1;
    }
    cout<<"load python module success\n";
    Py_Finalize();
    return 0;
}

编译指令:g++ -o a -fPIC -shared a.cpp -I/usr/include/python2.7 -L/usr/lib/python2.7 -lpython2.7 执行时段错误
编译指令:g++ -o a a.cpp -I/usr/include/python2.7 -L/usr/lib/python2.7 -lpython2.7 正确执行

不加 -fPIC -shared 参数执行是没问题的,但是这个c++库文件就是用来供python调用的,不能不加。。。
请各位大神看有没有解决办法,万谢

【热门文章】
【热门文章】