I'm having trouble achieving this. What I'm stuck with is trying to expose Modules written in C++ to an embedded python interpreter.
I'm using boost::python, but I'm not sure what I'm supposed to do for this, as the documentation seems to be lacking, to say the least.
What I want is to expose some C++ code with BOOST_PYTHON_MODULE, and then access that from the same application. However I can't get it to import. What I've got, which seem the closest (just relevant part):
#include <python/interpreter.hpp>
bp::object blag() {
return bp::str("Thingy");
}
BOOST_PYTHON_MODULE(modthingy) {
bp::def("blag", &blag);
}
Interpreter::Interpreter() {
Py_UnbufferedStdioFlag = 1;
Py_Initialize();
try {
init_module_modthingy();
} catch (bp::error_already_set) {
PyErr_Print();
}
main_module = bp::import("__main__");
main_namespace = main_module.attr("__dict__");
}
But that prints the Error AttributeError: 'NoneType' object has no attribute '__dict__'
And I can't import the module later.
How should this be structured?
EDIT: Ok, so the closest I got was one of the methods in the accepted answer:
PyImport_AppendInittab("modthingy", &PyInit_modthingy);
Py_Initialize();
However, this doesn't seem particularly useful in my case, as I'd like to be able to add/import modules after the Initialize function. I'm going to look into a few things, namely:
- See if I can get the suggested approach for python 2 working in python 3
- See if I can nicely structure my game to require naming all of the modules before Py_Initialize
I'll update this post with my findings.