[C++-sig] using intrusive_ptr objects with boost python

Roman Yakovenko roman.yakovenko at gmail.com
Sat Jun 23 20:08:55 CEST 2007


On 6/19/07, Jeff Webb <jeff.webb at nta-inc.net> wrote:
> Let me first say that I am extremely impressed with boost python's elegant
and powerful design.  I would not have thought that it was possible to
integrate C++ and python code in such a nice manner.  Thanks for all the
hard work and thoughtful design.
>
> I am writing a C++ library from scratch, and I want to develop boost
python bindings for it simultaneously.  My C++ library will instantiate many
small objects that hold references to other objects.  I had come up a
consistent scheme for managing the objects using C++, but when I started
trying to wrap the library using boost, I found that this scheme didn't mesh
well with python's reference counting form of memory management.  After
quite a bit of reading, experimentation, and contemplation, it appears to me
that using reference-counting smart pointers in C++ would be the most
consistent and seamless way to provide a rich python binding for this type
of library.  Do others agree with this assertion?

This is was my experience.


> I wrote a simple test library using shared_ptr objects and found that
wrapping it was very natural.  Things 'just worked' as I would have
hoped.  The source code for this library is attached to this email as
's_ptr_lib.cpp'.  A sample ipython session is shown below.

Boost.Python has perfect support for boost::shared_ptr and in some cases to
std::auto_ptr

> Very nice!  Unfortunately, I think the overhead of using a shared_ptr will
be too high, since my library will instantiate many small objects.

It looks like you know what you are doing, but don't you think this is a
premature optimization?

> Am I on the right path here?  Is it possible to make the intrusive_ptr
work as seamlessly as the shared_ptr, or is there some fundamental problem
with what I hope to achieve?

It is possible to create code that will work pretty closed to as shared_ptr
one. If you search this mailing list you will even find the implementation.

> Is there some technical reason why this is not already implemented, or is
it just that there hasn't been a need up to this point?

Boost.Python has special code that treats shared_ptr here and there.

> If I should continue down this path, can someone give me a skeleton of the
code I need to write (and how to get it 'registered') to provide all the
functionality that exists for the shared_ptr class?
>

Just search this mailing list for "intrusive_ptr" and you will find many
useful posts.

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20070623/47641676/attachment.htm>


More information about the Cplusplus-sig mailing list