|
Size: 1760
Comment: Fix code example wiki markup.
|
Size: 1866
Comment: the c++ code did not compile at all the way it was presented
|
| Deletions are marked like this. | Additions are marked like this. |
| Line 41: | Line 41: |
| #include <boost/shared_ptr.h> | #include <string> #include <boost/shared_ptr.hpp> #include <boost/python.hpp> |
| Line 43: | Line 46: |
| using namespace std; using namespace boost::python; |
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" can be handled by Python's garbage collection by using the manage_new_object storage policy:
struct A {
static A* create () { return new A; }
std::string hello () { return "Hello, is there anybody in there?"; }
};
BOOST_PYTHON_MODULE(shared_ptr)
{
class_<A>("A",no_init)
.def("create",&A::create,return_value_policy<manage_new_object>())
.staticmethod("create")
.def("hello",&A::hello)
;
}A sample python program:
from pointer import * an_A = A.create() print an_A.hello()
Smart pointers
Smart pointers, e.g. boost::shared_ptr<T>, is another common way to give away ownership of objects in C++. Theese kind of smart pointer are automatically handled, if you declare their existence, when declaring the class to boost.python.
E.g.
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/python.hpp>
using namespace boost;
using namespace std;
using namespace boost::python;
struct A {
static shared_ptr<A> create () { return shared_ptr<A>(new A); }
std::string hello () { return "Just nod if you can hear me!"; }
};
BOOST_PYTHON_MODULE(shared_ptr)
{
class_<A, shared_ptr<A> >("A",init<>())
.def("create",&A::create )
.staticmethod("create")
.def("hello",&A::hello)
;
}A sample python program:
from shared_ptr import * an_A = A.create() print an_A.hello()
