Python Embedded C++

后端 未结 1 524
醉梦人生
醉梦人生 2021-01-28 14:38

I have read few tutorial on python embedded c++. I had refer back to python object. https://docs.python.org/3/c-api/function.html

Python script:

import p         


        
相关标签:
1条回答
  • 2021-01-28 15:05

    If I understand correctly, you want your C++ code to call your Python test() function and get the string result of that function back so the C++ code can do something with it. If so, I think something like this would do the trick for you:

     std::string data;
     char fileName[] = "my_test_python_script.py";
     PyObject * moduleObj = PyImport_ImportModule(filename);
     if (moduleObj)
     {
        char functionName[] = "test";
        PyObject * functionObj = PyObject_GetAttrString(moduleObj, functionName);
        if (functionObj)
        {
           if (PyCallable_Check(functionObj))
           {
              PyObject * argsObject = PyTuple_New(0);
              if (argsObject)
              {
                 PyObject * resultObject = PyEval_CallObject(functionObj, argsObject);
                 if (resultObject)
                 {
                    if ((resultObject != Py_None)&&(PyString_Check(resultObject))) 
                    {
                        data = PyString_AsString(resultObject);
                    }
                    Py_DECREF(resultObject);
                 }
                 else if (PyErr_Occurred()) PyErr_Print();
    
                 Py_DECREF(argsObject);
              }
           }
           Py_DECREF(functionObj);
        }
        else PyErr_Clear();
    
        Py_DECREF(moduleObj);
     }
    
     std::cout << "The Python test function returned: " << data << std::endl;
    
    0 讨论(0)
提交回复
热议问题