c – 在boost python中使用自定义智能指针
发布时间:2020-12-16 05:03:07 所属栏目:百科 来源:网络整理
导读:我想使用Boost :: Python公开python中自定义智能指针包装的对象 警告 自定义智能指针的现有用法太普遍了 经济地升级到提升智能指针 我想使用几个位置描述的自动解除引用技术 问题是我似乎无法做到这一点.这是一个示例代码: LegacyCode :: Ptr – 传统的智能
我想使用Boost ::
Python公开python中自定义智能指针包装的对象
警告 >自定义智能指针的现有用法太普遍了 问题是我似乎无法做到这一点.这是一个示例代码: LegacyCode :: Ptr – >传统的智能指针代码 LegacyCode :: Session – >包含在传统智能指针中的遗留对象 namespace boost { namespace python { template <class T> T* get_pointer(LegacyCode::Ptr<T> const& p) { return p.get(); } template <typename T> struct pointee<LegacyCode::Ptr<T> > { typedef T type; }; }}* BOOST_PYTHON_MODULE(pyro) { using namespace boost::python; class_<LegacyCode::Session,LegacyCode::Ptr<LegacyCode::Session>>("Session") .def("get_type",&LegacyCode::Session::getType); } 解决方法
这是一个完整的例子.你几乎拥有它 – 你必须从boost :: python命名空间中删除get_pointer().
#include <boost/python.hpp> // dummy smart ptr class template <typename T> class Ptr { public: typedef T element_type; Ptr(): px(0) {} Ptr(T* p): px(p) {} // base operators T* operator->() { return px; } const T* operator->() const { return px; } T& operator*() { return *px; } const T& operator*() const { return *px; } // getters T* get() { return px; } const T* get() const { return px; } private: T* px; }; // a dummy class that will be held by your custom smart pointer class Session { public: Session(int value) : value_(value) {} virtual ~Session() {} // a few methods to play with the class int value() const { return value_; }; void value(int value) { value_ = value; } private: int value_; }; // this emulates methods actually using your smart pointers void print_value_1(const Ptr<Session>& s) { std::cout << "[by const reference] The value of this session is " << s->value() << std::endl; } void print_value_2(Ptr<Session> s) { std::cout << "[by value] The value of this session is " << s->value() << std::endl; } // here comes the magic template <typename T> T* get_pointer(Ptr<T> const& p) { //notice the const_cast<> at this point //for some unknown reason,bp likes to have it like that return const_cast<T*>(p.get()); } // some boost.python plumbing is required as you already know namespace boost { namespace python { template <typename T> struct pointee<Ptr<T> > { typedef T type; }; } } // now the module BOOST_PYTHON_MODULE(example) { using namespace boost::python; class_<Session,Ptr<Session>,boost::noncopyable>("Session",init<int>()); def("print_value_1",&print_value_1); def("print_value_2",&print_value_2); } 您可以使用以下python代码对此进行测试: import example s = example.Session(27) example.print_value_1(s) example.print_value_2(s) 我们通过示例演示boost.python将根据需要正确运行转换. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |