I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library.
While wrapping the basic library API calls is quite simple (nothing special, just regular function calls and very common parameters), I don't know how to properly wrap the initialization/cleanup functions:
As it stands, my C++ library requires the caller to first call mylib::initialize()
when the program starts, and to call mylib::cleanup()
before it ends (actually there is also an initializer object that takes care of that, but it is probably irrelevant).
How should I wrap this using boost python ?
Forcing a Python user to call mymodule.initialize()
and mymodule.cleanup()
seems not very pythonic. Is there any way to that in an automatic fashion ? Ideally, the call to initialize()
would be done transparently when the module is imported and the call to cleanup()
also done when the python script ends.
Is there any way to do that ? If not, what is the most elegant solution ?
Thank you.
You could try to do a guard object and assign it to a hidden attribute of your module.
struct MyLibGuard
{
MyLibGuard() { myLib::initialize();}
~MyLibGuard() { myLib::cleanup();}
};
using namespace boost::python;
BOOST_PYTHON_MODULE(arch_lib)
{
boost::shared_ptr<MyLibGuard> libGuard = new MyLibGuard();
class_<MyLibGuard, boost::shared_ptr<MyLibGuard>, boost::noncopyable>("MyLibGuard", no_init);
scope().attr("__libguard") = libGuard;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With