Question

I am writing a small program with the Python C/API, which basically calls a simple Python script. Here's the code:

#include <Python.h>

PyObject *pName, *pModule, *pDict, *pFunc;

int main() {

    Py_Initialize();
    pName = PyString_FromString("simplemodule");
    pModule = PyImport_Import(pName);
    pDict = PyModule_GetDict(pModule);
    pFunc = PyDict_GetItemString(pDict, "simplefunction");

    if(PyCallable_Check(pFunc)) {

        PyObject_CallObject(pFunc, NULL);


    } else {

        PyErr_Print();

    }

    Py_DECREF(pName);
    Py_DECREF(pModule);

    Py_Finalize();

    return 0;
}

Now, here is the code for simplemodule.py:

def simplefunction():
    m = 5*5
    return m

My question is: How can I assign the variable m to a C++ variable, so I can use it in C++?

Was it helpful?

Solution

Use PyInt_AsLong to convert the return value to C long.

...
if (PyCallable_Check(pFunc)) {
    PyObject *res = PyObject_CallObject(pFunc, NULL);
    if (res != NULL) {
        long n = PyInt_AsLong(res); // <---------
        cout << n << endl;
    } else {
        PyErr_Print();
    }
    ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top