ubuntu c++调用python编译成的so库并获取返回值

参考博客:ubuntu c++调用python函数并获取返回值_c++调用python方法返回string-CSDN博客

 参考网上的将python编译成so文件的方法

c++调用python编译生成的库

    
    Py_Initialize();
    // 获取sys.path
    PyObject* sys_module = PyImport_ImportModule("sys");
    if (sys_module == NULL) {
        PyErr_Print();
        return 1;
    }
    PyObject* sys_path = PyObject_GetAttrString(sys_module, "path");
    if (sys_path == NULL) {
        PyErr_Print();
        return 1;
    }
    // 将新目录添加到sys.path    python编译生成的so文件的路径
    PyObject* new_path = PyUnicode_FromString("/usr/lib/python3.6/site-packages");
    if (new_path == NULL) {
        PyErr_Print();
        return 1;
    }
    
    if (PyList_Append(sys_path, new_path) != 0) {
        PyErr_Print();
        return 1;
    }
    //so文件模块的名字   
    PyObject* module_name = PyUnicode_FromString("example_module");
    PyObject* module = PyImport_Import(module_name);
    Py_DECREF(module_name);
    if (module == NULL) {
        PyErr_Print();
        std::cerr << "Failed to load module"<< std::endl;
        return 1;
    }
    //调用的函数
    PyObject* add_func = PyObject_GetAttrString(module, "data_parsing");
    Py_DECREF(module);
    if (add_func == NULL) {
        PyErr_Print();
        std::cerr << "Failed to get function 'add'"<< std::endl;
        return 1;
    }
    //传入一个参数 参数为string类型
    PyObject* args = PyTuple_New(1);
    PyObject* pValue = Py_BuildValue("s", jsonData.c_str());
    PyTuple_SetItem(args, 0, pValue);
    PyObject* result = PyObject_CallObject(add_func, args);
    Py_DECREF(args);
    Py_DECREF(add_func);
    if (result == NULL) {
        PyErr_Print();
        std::cerr << "Failed to call function 'add'"<< std::endl;
        return 1;
    }

    string returnPythonString = "";
    Json::Reader jreader;
    Json::Value jvalue;

    if (result && PyUnicode_Check(result)) {
        returnPythonString = PyUnicode_AsUTF8(result);
        //cout<<"python return : "<<returnPythonString<<endl;

        jreader.parse(returnPythonString, jvalue);
    }

    return jvalue;

相关推荐

  1. ubuntu c++调用pythonso获取返回

    2024-04-08 01:58:03       19 阅读
  2. 用GCC把C语言文件Intel语法汇编代码

    2024-04-08 01:58:03       12 阅读
  3. 在C#中调用C++函数返回const char*类型

    2024-04-08 01:58:03       35 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-08 01:58:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-08 01:58:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-08 01:58:03       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-08 01:58:03       20 阅读

热门阅读

  1. 服务器硬件基础知识202404

    2024-04-08 01:58:03       24 阅读
  2. 【python】Flask Web框架

    2024-04-08 01:58:03       24 阅读
  3. 【00150】金融理论与实务-2023年10月自考真题

    2024-04-08 01:58:03       21 阅读
  4. python格式化输出

    2024-04-08 01:58:03       21 阅读
  5. 使用Git进行持续交付:如何使用CI/CD自动化流程

    2024-04-08 01:58:03       12 阅读
  6. C# 系统学习(实例计算器)

    2024-04-08 01:58:03       17 阅读
  7. GO并发总是更快吗?

    2024-04-08 01:58:03       12 阅读