更新时间:2023-02-17 15:00:59
好吧,这是基于原始C ++ sig帖子的来回可选转换器的全部内容,但重写后使用了高级boost.python API(对不起,很奇怪间距).
Ok here is the entire to and from optional converter based on the original C++ sig post but rewritten to use the high level boost.python API (sorry about the weird spacing).
template<typename T>
struct optional_ : private boost::noncopyable
{
struct conversion :
public boost::python::converter::expected_from_python_type<T>
{
static PyObject* convert(boost::optional<T> const& value) {
using namespace boost::python;
return incref((value ? object(*value) : object()).ptr());
}
};
static void* convertible(PyObject *obj) {
using namespace boost::python;
return obj == Py_None || extract<T>(obj).check() ? obj : NULL;
}
static void constructor(PyObject *obj,
boost::python::converter::rvalue_from_python_stage1_data *data)
{
using namespace boost::python;
void *const storage =
reinterpret_cast<
converter::rvalue_from_python_storage<boost::optional<T> >*
>(data)->storage.bytes;
if(obj == Py_None) {
new (storage) boost::optional<T>();
} else {
new (storage) boost::optional<T>(extract<T>(obj));
}
data->convertible = storage;
}
explicit optional_() {
using namespace boost::python;
if(!extract<boost::optional<T> >(object()).check()) {
to_python_converter<boost::optional<T>, conversion, true>();
converter::registry::push_back(
&convertible,
&constructor,
type_id<boost::optional<T> >(),
&conversion::get_pytype
);
}
}
};