在boost python中使用自定义智能指针
Using custom smart pointers in boost python
我想在python中使用Boost:: python
将对象封装在自定义智能指针中警告
- 现有的自定义智能指针的使用太普遍了经济升级到boost智能指针
- 我想使用在几个地方描述的自动解引用技术
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
将根据需要正确运行转换。
相关文章:
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++自定义比较函数
- 如何比较自定义类的std::变体
- std::设置自定义比较器
- 如何避免自定义 STL 向量类的智能指针 delete[] 异常?
- C++自定义智能指针
- 智能指针自定义删除器中的处理条件
- 如何正确使用带有智能指针和自定义类的映射作为键和值
- 使用 std::sort 对自定义类的智能指针进行排序
- Visual Studio中智能指针对象的自定义视图
- C++在boost python中使用带有命名空间的自定义智能指针
- 如何编写一个可以接受函数指针和/或函子的类,就像智能指针对自定义deleter所做的那样
- 使用自定义删除器增强智能指针
- C++——智能指针和自定义内存分配困境
- 自定义UI元素使用的智能指针选择
- 访问智能指针时的自定义操作
- 如何在c++中设置智能感知来显示自定义数据类型
- 将 std::unique_ptr<void> 与自定义删除器一起使用作为智能无效*
- 在boost python中使用自定义智能指针