Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Boost.Python - <register_ptr_to_python.hpp>

Boost.Python

Header

Contents

Introduction
Functions
register_ptr_to_python
Example(s)

Introduction

supplies register_ptr_to_python, a function template which registers a conversion for smart pointers to Python. The resulting Python object holds a copy of the converted smart pointer, but behaves as though it were a wrapped copy of the pointee. If the pointee type has virtual functions and the class representing its dynamic (most-derived) type has been wrapped, the Python object will be an instance of the wrapper for the most-derived type. More than one smart pointer type for a pointee's class can be registered.

Note that in order to convert a Python X object to a smart_ptr& (non-const reference), the embedded C++ object must be held by smart_ptr, and that when wrapped objects are created by calling the constructor from Python, how they are held is determined by the HeldType parameter to class_<...> instances.

Functions

template 
void register_ptr_to_python() 
Requires: P is Dereferenceable.
Effects: Allows conversions to-python of P instances.

Example(s)

C++ Wrapper Code

Here is an example of a module that contains a class A with virtual functions and some functions that work with boost::shared_ptr.
struct A
{
    virtual int f() { return 0; }
};

shared_ptr New() { return shared_ptr( new A() ); }

int Ok( const shared_ptr& a ) { return a->f(); }

int Fail( shared_ptr& a ) { return a->f(); }

struct A_Wrapper: A
{
    A_Wrapper(PyObject* self_): self(self_) {}
    int f() { return call_method(self, "f"); }    
    int default_f() { return A::f(); }    
    PyObject* self;
};

BOOST_PYTHON_MODULE(register_ptr)
{
    class_("A")
        .def("f", &A::f, &A_Wrapper::default_f)
    ;
    
    def("New", &New);
    def("Ok", &Call);
    def("Fail", &Fail);
    
    register_ptr_to_python< shared_ptr >();
} 

Python Code

>>> from register_ptr import *
>>> a = A()
>>> Ok(a)     # ok, passed as shared_ptr
0
>>> Fail(a)   # passed as shared_ptr&, and was created in Python!
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: bad argument type for built-in operation
>>>
>>> na = New()   # now "na" is actually a shared_ptr 
>>> Ok(a)
0
>>> Fail(a)
0
>>>
If shared_ptr is registered as follows:
    class_ >("A")
        .def("f", &A::f, &A_Wrapper::default_f)
    ;            
There will be an error when trying to convert shared_ptr
to shared_ptr:
>>> a = New()
Traceback (most recent call last):
File "", line 1, in ?
TypeError: No to_python (by-value) converter found for C++ type: class boost::shared_ptr
>>>    

Revised 24 Jun, 2003

© Copyright Dave Abrahams 2002.