【问题标题】:Boost python passing named parameter to member classBoost python将命名参数传递给成员类
【发布时间】:2021-03-15 23:20:18
【问题描述】:

我有以下结构:

struct StuffMaker {

  static std::string makeStuff(po::dict options = {})
  {

    //makes some stuff
  }

};

我想在我的 python 模块中公开它来做一些事情:


BOOST_PYTHON_MODULE(stuffMakers)
{
  po::class_<StuffMaker>("StuffMaker")
    .def("create", &StuffMaker::makeStuff, (arg("options")));
}

但是当我编译解释器并传递以下代码时:

import stuffMakers
maker = stuffMakers.StuffMaker()
maker.makeStuff(options = {})

我得到了第一个参数的类型错误,预期是选项的字典,但是我的 cpp 得到了“self”引用——所以第一个参数是 StuffMaker 类。基本上这是我的问题,我如何忽略 c++ 绑定中的第一个参数,或者我在定义中的“arg”前面放什么来正确处理“self”参数?

错误如下:

Traceback (most recent call last):
  File "<string>", line 6, in <module>
Boost.Python.ArgumentError: Python argument types in
    StuffMaker.makeStuff(StuffMaker)
did not match C++ signature:
    create(boost::python::dict options)

【问题讨论】:

  • 你能分享一下错误吗
  • @GabeRon 更新描述

标签: c++ boost-python


【解决方案1】:

为了传递 self 参数,您至少有 2 个有效的签名选择:

struct StuffMaker {

  static std::string makeStuff(StuffMaker self, po::dict options = {})
  {

    //makes some stuff
  }

  //alternatively
  static std::string makeStuff(StuffMaker* self, po::dict options = {})
  {

    //makes some stuff
  }
};

这个签名工作正常,注册会自动处理隐式参数,所以注册命名参数你需要做的就是以下更改:

BOOST_PYTHON_MODULE(geometry_creators)
{
  po::class_<StuffMaker>("StuffMaker")
    .def("makeStuff", &StuffMaker::makeStuff, (po::arg("options")), "do some stuff with named parameter");
}

参数列表中的第一个参数是自动添加的,因此无需在 def 注册中隐式添加。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    相关资源
    最近更新 更多