[C++-sig] Re: module unloading callback?

Nicodemus nicodemus at esss.com.br
Tue Jan 20 01:08:36 CET 2004


Mike Rovner wrote:

>Daniel Holth wrote:
>  
>
>>I've been wrapping a library thats documentation says you should
>>init() and free() some internal data structures before and after you
>>use it.  I can put code in BOOST_MODULE_INIT to call init, but where
>>would I put the tear-down code?  Thanks.
>>    
>>
>
>That is very common problem for many libraries. They usually provide
>  libInit(...)
>  libFinish(...)
>
>My approach is simply wrap them as (module) lib functions:
>  Init(...) and Finish(...)
>for the user to call manually.
>
>Optionaly as you said, 'init' is called automatically on module init.
>That is really depends on library usage model.
>But because python _never_ unloads its modules you can't put 'finish'
>call anywere to be called automatically.
>  
>

One approach is to have a python wrapper for your extension module, that 
calls the Init() on import and register the Finish function in the 
atexit module:

# file myext.py
from _myext import * # bring the _myext namespace

InitLib()

import atexit
atexit.register(FinishLib)

The user is then required to use only "import myext". This also allows 
you to put some Python functionality in your module.

Also, one can call InitLib() inside BOOST_PYTHON_MODULE(), which I find 
best specially in the case in failling to properly initializing the 
library can cause crashes in Python.

Regards,
Nicodemus.





More information about the Cplusplus-sig mailing list