1

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++?

jndok
  • 909
  • 3
  • 14
  • 28

1 Answers1

2

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();
    }
    ...
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Thanks! It works perfectly. And if the module function returns a string, should I use something like `PyString_AsString`? – jndok Jan 06 '14 at 11:42
  • @jndok, Yes, use [`PyString_AsString`](http://docs.python.org/2/c-api/string.html#PyString_AsString). BTW, it returns `char *`, not C++ `string`. – falsetru Jan 06 '14 at 11:45