首页 > 解决方案 > Boost python将命名参数传递给成员类

问题描述

我有以下结构:

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)

标签: c++boost-python

解决方案


为了传递 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 注册中隐式添加它。


推荐阅读