[C++-sig] Custom WeakPtrs and "None"
haller at ableton.com
Tue Nov 16 21:47:46 CET 2004
I'm not sure if this is more of a Python question than a Boost.Python
We have our own intrusive refcount mechanism in the classes that we want
to wrap with Boost.Python. We have weak pointers to these classes that
go NULL when the pointee is deleted.
Because of the intrusive refcounts, we can easily pass raw pointers
instead of shared pointers as function arguments and return values in
C++; I find this more convenient than having to pass shared pointers all
the time. The caller of a function-returning-a-raw-ptr is free to
decide if he wants to keep the returned object in a shared pointer or a
Now, when exposing these functions to python, we want to make sure that
all such returned objects are held in weak pointers on the python side.
(We do all our application logic in C++, and merely want to add a
scripting layer in python that is allowed to manipulate the data model
in certain restricted ways; we are not going to create or delete objects
from python.) This is easy to do by writing thin wrapper functions that
simply return a weak ptr constructed from the raw pointer, and ".def"ing
those instead of the real functions; register_ptr_to_python does the
rest, which is very nice.
The only problem is that when the object goes away, the "weak pointer"
on the Python side isn't set to "None". Of course, the wrapped C++ weak
pointer is set to NULL, but the python variable isn't aware of that
unless you try to access properties or call methods on it, in which case
it throws an exception. It would be very nice if a comparison with None
would return true for a weak pointer that has been set to NULL.
Is there a way to achieve that? Does it help if I post some example
code to illustrate that lengthy prose above?
More information about the Cplusplus-sig