Search code examples
pythonc++python-embedding

How to Copy PyObject*?


I am calling a Python Function from a C++ function like below.

void CPPFunction(PyObject* pValue)
{
  ...
  pValue = PyObject_CallObject(PythonFunction, NULL);
  ...
}

int main()
{
  PyObject *pValue = NULL;
  CPPFunction(PValue);
  int result_of_python_function = Pylong_aslong(PValue);
}

I would like to access the return value of python function outside the CPPFunction. since scope of PObject* returned by PyObject_CallObject is within CPPFunction, how to access the value outside CPPFunction?


Solution

  • Return it from the function like you would anywhere else.

    PyObject* CPPFunction()
    {
        // ...
        PyObject* pValue = PyObject_CallObject(PythonFunction, NULL);
        // ...
        return pValue;
    }
    
    int main()
    {
      PyObject *value = CPPFunction();
      int result_of_python_function = Pylong_aslong(value);
    }