首页 > 解决方案 > 如何将调用 python 的 c++ 代码包装为 .dll 或 .so?

问题描述

我想将我的 c++ 代码包装为 .so 和 .dll 文件。我知道如何将 c++ 代码包装为动态库,但是我的 c++ 代码正在调用 python,通常我们称之为嵌入 python。我写了一个基本的简单代码。蟒蛇代码:

  def init_test(env, mode):
      print(env)
      print(mode)
      return 1

c++代码调用python:

#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <iostream>
#include <exception>

/**
 * @description: run risk performance use Python
 * @param {string} env
 * @param {string } mode
 * @return {*}
 */
extern "C" int init_python_test(char* env,  char* mode) {
    std::cout << "start" <<std::endl;
    if(Py_IsInitialized == 0){
        std::cout << "not init" << std::endl;
    }
    else{
        std::cout << "init already" <<std::endl;
        //std::cout << Py_FinalizeEx() <<std::endl;
        Py_Finalize();
    }
    std::cout << "init:"<<Py_IsInitialized() << std::endl;
    Py_Initialize();
    PyErr_Print();
    std::cout <<"second" <<std::endl;
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");
    std::cout <<"ok" <<std::endl;

    //int res;
    PyObject *pModule,*pFunc = NULL;
    PyObject *pArgs, *pValue = NULL;
    pModule = PyImport_ImportModule("mini");//0x7ffff64b9cc0
    if(!pModule)
        std::cout << "can't open python file" << std::endl;
    PyErr_Print();
    pFunc = PyObject_GetAttrString(pModule, "init_test"); 
    PyErr_Print();

    if(pFunc && PyCallable_Check(pFunc)){
        
        PyErr_Print();
        
        pValue = PyObject_CallObject(pFunc, Py_BuildValue("(ss)", env, mode));
        PyErr_Print();
    
    }
    Py_FinalizeEx();
    return 1;
}

int main(){
    char  *env = (char*)"prod";
    char * mode = (char*)"prod";
    init_python_test(env, mode);
    std::cout << "ok" <<std::endl;

}

我能够使用与 python 动态库链接的 g++ 命令正确运行我的 c++ 代码。我可以使用 g++ 将我的 c++ 代码包装为 .so 文件。当我使用另一个 c++ 代码和 python 代码来测试 init_python_test 函数时。当代码运行到 Py_Initialize() 时会发生分段错误。

那么,如何解决这个问题呢?我是否用 g++ 正确包装了 c++ 代码?这是我的外壳。

g++ -fPIC -shared -Wall -o libtest.so ./mini_test.cpp -DLINUX -D_GLIBCXX_USE_CXX11_ABI=0 -I /usr/include/python3.8 -L/usr/lib/python3 -L/usr/lib/python3.8 -lpython3.8

有人帮助我!请!!!感谢你!!!!

标签: pythonc++g++python-embedding

解决方案


推荐阅读