c++ - 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)
解决方案
为了传递 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 注册中隐式添加它。
推荐阅读
- ruby-on-rails - puma 的 redmine 错误:错误转换执行错误(NoMethodError(未定义的方法 `do' for false:FalseClass))
- reactjs - 如何根据 css 媒体查询重定向到 next.js 中的另一个页面?
- linux - pthread_join 无限期挂起 __lll_lock_wait_private()
- ionic3 - 使用 OpenVidu 仅创建音频通话
- pandas - 基于 Pandas 中的 groupby 为数据框中的日期添加和填充行
- amazon-web-services - Amazon S3 存储桶策略和 CORS 不起作用
- neo4j - 无法连接到 Neo4j 3.5.14 社区版服务器
- python - 根据标题中的关键字对服装进行分类
- angular - 在响应时调试信号 R
- html - 如何在 CSS 的内联块中移动文本?