1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
[section boost/python/register_ptr_to_python.hpp]
[section Introduction]
<boost/python/register_ptr_to_python.hpp> 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<X>&` (non-const reference), the embedded C++ object must be held by `smart_ptr<X>`, 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.
[endsect]
[section Function `register_ptr_to_python`]
``
template <class P>
void register_ptr_to_python()
``
[variablelist
[[Requires][`P` is [link concepts.dereferenceable Dereferenceable].]]
[[Effects][Allows conversions to-python of P instances. ]]
]
[endsect]
[section Example]
Here is an example of a module that contains a class A with virtual functions and some functions that work with boost::shared_ptr<A>.
In C++:
``
struct A
{
virtual int f() { return 0; }
};
shared_ptr<A> New() { return shared_ptr<A>( new A() ); }
int Ok( const shared_ptr<A>& a ) { return a->f(); }
int Fail( shared_ptr<A>& a ) { return a->f(); }
struct A_Wrapper: A
{
A_Wrapper(PyObject* self_): self(self_) {}
int f() { return call_method<int>(self, "f"); }
int default_f() { return A::f(); }
PyObject* self;
};
BOOST_PYTHON_MODULE(register_ptr)
{
class_<A, A_Wrapper>("A")
.def("f", &A::f, &A_Wrapper::default_f)
;
def("New", &New);
def("Ok", &Call);
def("Fail", &Fail);
register_ptr_to_python< shared_ptr<A> >();
}
``
In Python:
``
>>> from register_ptr import *
>>> a = A()
>>> Ok(a) # ok, passed as shared_ptr<A>
0
>>> Fail(a) # passed as shared_ptr<A>&, and was created in Python!
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation
>>>
>>> na = New() # now "na" is actually a shared_ptr<A>
>>> Ok(a)
0
>>> Fail(a)
0
>>>
``
If shared_ptr<A> is registered as follows:
``
class_<A, A_Wrapper, shared_ptr<A> >("A")
.def("f", &A::f, &A_Wrapper::default_f)
;
``
There will be an error when trying to convert shared_ptr<A> to shared_ptr<A_Wrapper>:
``
>>> a = New()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: No to_python (by-value) converter found for C++ type: class boost::shared_ptr<struct A>
>>>
``
[endsect]
|