2

I'm writing a small program (the one below) that embeds python in a C++ code.

#include <Python.h>

int main()     
{

    int x;
    Py_Initialize();

    const char* pythonScript = "print 'Start'"
    PyRun_SimpleString(pythonScript);

    /*
    assign a python variable 'n' to 'x' i.e n=x
    */

    Py_Finalize();
    return 0; 

}

My requirement here is that i assign the python variable 'n' the value of C++ variable 'x'. Is there a way to do this?

Thanks in advance.

1

1 Answer 1

1

The following fragment should work (untested):

PyObject *main = PyImport_AddModule("__main__"); // borrowed
if (main == NULL)
    error();
PyObject *globals = PyModule_GetDict(main); // borrowed
PyObject *value = PyInt_FromLong(x);
if (value == NULL)
   error();
if (PyDict_SetItemString(globals, "n", value) < 0)
   error();
Py_DECREF(value);
Sign up to request clarification or add additional context in comments.

Comments

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.