これは完全に機能する例です。名前空間get_pointer()
からを削除する必要があります。boost::python
#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
必要に応じて変換を正しく実行する例を示します。