Revision 1 as of 2007-11-24 19:58:16

Clear message

Pointers and smart pointers

Since Python handles memory allocation and garbage collection automatically, the concept "pointer" is not meaningful within Python. However, many C++ API exposes either raw pointers or shared pointers, and to wrap such APIs one would need to deal with pointers.

Pointers (raw C++ pointers)

The life time of C++ objects created by "new A" kan be handled by Pythons garbage collection by using the manage_new_object storage policy:

{{{struct A {

};

BOOST_PYTHON_MODULE(shared_ptr) {

} }}}

A sample python program:

from pointer import *
an_A = A.create()
print A.hello()

Smart pointers

Smart pointers, e.g. boost::shared_ptr<T>, is another common way to give away ownership of objects in C++. The following suggests a way to handle shared_ptr objects in Python, introducing the notation (+ptr).foo() in python to immitate C++'s (*ptr).foo():

{{{#include <boost/shared_ptr.h> using namespace boost;

struct A {

};

BOOST_PYTHON_MODULE(shared_ptr) {

} }}}

A sample python program:

from shared_ptr import *
an_A = A_ptr.create()
print (+an_A).hello()

Unable to edit the page? See the FrontPage for instructions.