[C++-sig] wrapping reference to c++ object

David Abrahams dave at boost-consulting.com
Mon Mar 17 22:30:57 CET 2003


harold fellermann <harold at imb-jena.de> writes:

>> One way, but not neccessarily a safe one, to get a Python object into
>> your list which wraps a reference to a C++ object, is
>>
>>      list.insert(0, boost::ref(cpp_obj));
>>
>> I say "not neccessarily safe" because there is nothing here to help
>> manage the lifetime of the C++ object properly; if it is destroyed
>> before the last Python reference you could crash the program with
>> Python code.
>
> This works. I use with_custodian_and_ward to bind the lifetime of
> cpp_obj to the object that inserts it into its list of references.

That doesn't work.  with_custodian_and_ward only binds the lifetime
of Python objects.   If the C++ object is held by a corresponding
Python object via raw pointer or reference (as with
boost::ref(cpp_obj)), it will not do anything to handle the problem I
mentioned above.

> There encountert no lifetime problem when using the classes as
> python extensions.

I think you were lucky.

> However, trying to use my classes with embedded python still
> troubles me.  The thing I don't understand is the following: when I
> insert a cpp_obj in python, I deal with a python::object because of
> the wrapper classes, which works fine. But when I use the same
> (unwrapped) classes for embedded python, any attempt to insert
> ref(cpp_obj) into my python::list still dumps.  What is the reason
> therefore? Is there a concept I haven't understood yet?

You haven't explained the problem well enough to know.  Code
(preferably minimal) helps.  Minimizing the code may also teach you
where you went wrong.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list