2

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!

5
  • Having global state is a bad idea generally - if you refactor to avoid this, the problem will go away. Commented Apr 22, 2015 at 9:25
  • @jonrsharpe I don't see how re-factoring is going to help, the Python script doesn't affect the running program at all, global value or not. Commented Apr 22, 2015 at 9:27
  • You haven't actually shown the code of the program whose state you are expecting to be modified. Are you embedding Python into your C++ program? (See boost.org/doc/libs/1_58_0/libs/python/doc/tutorial/doc/html/…) Commented Apr 22, 2015 at 10:11
  • @kloffy Yes, I've embedded it like the link you provided. Suffice to say, that states.count() should return a non-zero value. Commented Apr 22, 2015 at 11:01
  • "not affecting the parent program". How do you determine that? Provide an MCVE. Commented Apr 22, 2015 at 14:16

1 Answer 1

0

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

1 Comment

Thank you, the problem was that i was trying to use PyImport_ImportModule on a compiled version (*.pyd). Didn't know that PyImport_AppendInittab existed. Thank you!