python - g++编译加入-fPIC -shared参数后调用PyRun_SampleString段错误
天蓬老师
天蓬老师 2017-04-17 16:01:16
[Python讨论组]

为了实现抓包功能,用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调用的,不能不加。。。
请各位大神看有没有解决办法,万谢

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号