boost.python/HowTo on Python Wiki has an example of exposing C++ object as a module attribute inside BOOST_PYTHON_MODULE
:
namespace bp = boost::python;
BOOST_PYTHON_MODULE(example)
{
bp::scope().attr("my_attr") = bp::object(bp::ptr(&my_cpp_object));
}
To set the attribute outside of BOOST_PYTHON_MODULE
use
bp::import("example").attr("my_attr") = bp::object(bp::ptr(&my_cpp_object));
Now you can do in python something like
from example import my_attr
Of course, you need to register class of my_cpp_object
in advance (e.g. you can do this inside the same BOOST_PYTHON_MODULE
call) and ensure C++ object lifetime exceeds that of the python module. You can use any bp::object
instead of wrapping C++ one.
Note that BOOST_PYTHON_MODULE
swallows exceptions, so if you make a mistake, you don't receive any error indication and BOOST_PYTHON_MODULE
-generated function will just immediately return. To ease debugging of this case you can catch exceptions inside BOOST_PYTHON_MODULE
or temporary add some logging statement as a last line of BOOST_PYTHON_MODULE
to see that it is reached:
BOOST_PYTHON_MODULE(example)
{
bp::scope().attr("my_attr2") = new int(1); // this will compile
std::cout << "init finished\n"; // OOPS, this line will not be reached
}