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

1 Answer 1

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();
    }
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! It works perfectly. And if the module function returns a string, should I use something like PyString_AsString?
@jndok, Yes, use PyString_AsString. BTW, it returns char *, not C++ string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.