参考博客: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;