无法理解 boost python 函数导出中的语法

我现在正在查看来自 CARLA 模拟器 ( http://carla.org/ ) 的一些代码。

它使用 boost python 向 python 公开了许多 C++ 类和成员函数。但我无法理解下面几行的语法。


void export_blueprint() {

  using namespace boost::python;

  namespace cc = carla::client;

  namespace crpc = carla::rpc;

...

  class_<cc::ActorBlueprint>("ActorBlueprint", no_init)

    .add_property("id", +[](const cc::ActorBlueprint &self) -> std::string {

      return self.GetId();

    })

    .add_property("tags", &cc::ActorBlueprint::GetTags)

    .def("contains_tag", &cc::ActorBlueprint::ContainsTag)

    .def("match_tags", &cc::ActorBlueprint::MatchTags)

    .def("contains_attribute", &cc::ActorBlueprint::ContainsAttribute)

    .def("get_attribute", +[](const cc::ActorBlueprint &self, const std::string &id) -> cc::ActorAttribute {  

      return self.GetAttribute(id);

    })  // <=== THESE LINES

    .def("set_attribute", &cc::ActorBlueprint::SetAttribute)

    .def("__len__", &cc::ActorBlueprint::size)

    .def("__iter__", range(&cc::ActorBlueprint::begin, &cc::ActorBlueprint::end))

    .def(self_ns::str(self_ns::self))

  ;

}

下面的代码是什么


.def("get_attribute", +[](const cc::ActorBlueprint &self, 

     const std::string &id) -> cc::ActorAttribute { 

      return self.GetAttribute(id);

    })  

意思是?看起来 python 类 ActorBlueprint 的函数 get_attribute 函数正在被新(覆盖)定义为从 python 接口传递的新参数。我几乎可以肯定,但是否有任何关于此语法的文档?我在https://www.boost.org/doc/libs/1_63_0/libs/python/doc/html/tutorial/index.html 中找不到一个。


慕标5832272
浏览 226回答 1
1回答

米琪卡哇伊

我将逐个解释它。.def("get_attribute", ...) //method call with arguments+[](const cc::ActorBlueprint &self, const std::string &id) -> cc::ActorAttribute {...}// C++ lambda, passed to above method as second argumentreturn self.GetAttribute(id); // this is the lambda body您可以在此处阅读有关 lambda 语法的信息。此外,+在 lambda 前面的内容对您来说可能看起来很奇怪。它用于触发到普通旧函数指针的转换。在这里阅读。lambda 中的那个箭头-> cc::ActorAttribute指定了返回类型。它也可以用于普通的函数和方法。这是本机 C++ 语法,而不是特定于 boost 的东西。作为这段代码的结果,python 类ActorBlueprint的方法get_attribute将被定义。它将有一个字符串参数,并将执行 lambda 主体所做的操作(在这种情况下按 id 返回属性)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python