user2209008
user2209008

Reputation:

Calling C++ code via embedded Python

I have successfully created a Python module that appears to work in isolation, but doesn't affect the program that is running it.

I have the following module:

BOOST_PYTHON_MODULE(mandala)
{
    class_<state_mgr_t, state_mgr_t*, noncopyable>("states", no_init)
        .def("push", &state_mgr_t::push)
        .def("pop", &state_mgr_t::pop)
        .def("count", &state_mgr_t::count);

    scope().attr("states") = boost::python::object(boost::python::ptr(&states));
}

The states object is referencing a global value, states:

extern state_mgr_t states;

I can run the following script lines from within my program:

from mandala import states
states.count()
> 0

All of that is fine and whatnot, but I was expecting that running this python script would affect the actual state of the program that is running it. It appears as though Python is actually just dealing with it's own instance of states and not affecting the parent program.

Now I'm wondering if I've completely misunderstood what Boost.Python is capable of; I was expecting something similar to Lua, where I could modify the C++ program via scripts.

Is this not possible? Or am I doing something very wrong?

Thank you in advance!

Upvotes: 2

Views: 126

Answers (1)

kloffy
kloffy

Reputation: 2928

If you are embedding Python into your C++ program, it should be possible to access the instance from your script. Obviously, I don't have your full code, but have you tried something like this?

PyImport_AppendInittab("mandala", &initmandala);

Py_Initialize();

try {
    object main_module = import("__main__");
    object main_namespace = main_module.attr("__dict__");

    main_namespace.attr("states") = ptr(&states);

    object ignored = exec("print states.count()", main_namespace);

} catch(const error_already_set&) {
    PyErr_Print();
}

Upvotes: 0

Related Questions