通过<T> Boost.Python 作为内部引用公开 boost::可选或 None

Exposing boost::optional<T> via Boost.Python as internal reference or None

本文关键字:boost None 引用 gt lt Boost Python 通过 内部      更新时间:2023-10-16

我正在通过boost.python公开我的C 类。我的目的是揭示具有内部参考的用户定义类类型的成员变量。这效果很好,直到我决定引入一个类型boost的成员变量::可选&lt; t&gt;。

有几篇很棒的帖子显示了如何揭露boost ::可选&lt; t&gt;按值返回。具体来说,我已经实施了此转换器。我的代码的其他相关作品看起来像这样:

struct Bar {}
struct Foo {
  boost::optional<Bar> bar;
}
BOOST_PYTHON_MODULE(mymodule) {
  using namespace boost::python;
  python_optional<Bar>();  //registering the converter
  class_<Foo>("Foo")
    .add_property ( "bar", make_getter(&Foo::bar, return_value_policy<return_by_value>()), make_setter(&Foo::bar) )
  ;
}

我尝试用return_value_policy<reference_existing_object>()return_internal_reference<>()替换return_value_policy<return_by_value>()。两者都产生了Python TypeError:

>> import mymodule
>> foo = mymodule.Foo()
>> bar = foo.bar
TypeError: No Python class registered for C++ class boost::optional<Bar>

我的理解是,我现在正在引用boost ::可选&lt; t&gt;目的。但是,我注册的转换器未拨打,因为它期望BOOST ::可选&lt; t&gt;对象,而不是对这种对象的引用。我考虑过更改转换器,但我是新手,我真的不知道如何。有任何建议吗?

我通过在 struct Foo中添加一个getter,在boost ::可选的情况下将指针返回到对象,或者在boost的情况下返回nullptr,从而找到了解决方法。当&*bar返回const Bar*时,我必须使用const_cast

struct Bar {}
struct Foo {
  Bar* getBar() { return (bar ? const_cast<Bar*>(&*bar) : nullptr); };
  boost::optional<Bar> bar;
}
BOOST_PYTHON_MODULE(mymodule) {
  using namespace boost::python;
  python_optional<Bar>();  //registering the converter
  class_<Foo>("Foo")
    .add_property ( "bar", make_function(static_cast< Bar*(Foo::*)() >(&Foo::getBar), return_internal_reference<>() ), make_setter(&Foo::bar) )
  ;
}

,如果bar属于Foo Python的基类,则会产生这样的参数:

>> import mymodule
>> foo = mymodule.Foo()
>> foo.bar = mymodule.Bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument tpyes in
  None.None(Foo, Bar)
did not match C++ signature:
  None(FooBase {lvalue}, boost::optional<Bar>)

解决问题定义了Foobar的Getter和设置器。

struct Bar {}
struct FooBase {
  boost::optional<Bar> bar;
}
struct Foo : public FooBase {
  Bar* getBar() { return (bar ? const_cast<Bar*>(&*bar) : nullptr); };
  void setBar(const Bar* bar) { bar ?  this->bar = *bar : this->bar = boost::none; }
}
void (Foo::*foo_bar_set)(const Bar*) = &Foo::setBar;
BOOST_PYTHON_MODULE(mymodule) {
  using namespace boost::python;
  python_optional<Bar>();  //registering the converter
  class_<Foo>("Foo")
    .add_property ( "bar", make_function(static_cast< Bar*(Foo::*)() >(&Foo::getBar), return_internal_reference<>() ), foo_bar_set )
  ;
}