Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap an init/cleanup function in Boost python

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.

like image 597
ereOn Avatar asked Mar 23 '11 13:03

ereOn


1 Answers

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;

}
like image 169
Rod Avatar answered Nov 14 '22 23:11

Rod