C++ boost::python 普通指针和智能指针
由于Python自动处理内存分配和垃圾收集,因此“指针”的概念在Python中没有意义。boost::python可以方便地处理C++普通指针和智能指针。
普通指针(raw pointer)
C++接口返回普通指针需要用参数return_value_policy<manage_new_object>(),python会对该对象自动垃圾回收(garbage collection)。
struct A {
static A* create () { return new A; }
std::string hello () { return "Hello, is there anybody in there?"; }
};
BOOST_PYTHON_MODULE(pointer)
{
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)
使用智能指针(例如std::shared_ptr<T>)是在C++中放弃对象所有权的另一种常见方式。这是通过将保持类型作为模板参数包含到class_<>来实现的,如下例所示:
#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)
;
}
也可以使用register_ptr_to_python将shared_ptr注册到python。
BOOST_PYTHON_MODULE(shared_ptr)
{
class_<A>("A",init<>())
.def("create",&A::create )
.staticmethod("create")
.def("hello",&A::hello)
;
register_ptr_to_python<std::shared_ptr<A>>();
}
A sample python program:
from shared_ptr import *
an_A = A.create()
print an_A.hello()