问题 你如何将kwargs传递给boost-python包装函数?


我有一个带有此签名的python函数:

def post_message(self, message, *args, **kwargs):

我想从c ++调用函数并传递给它一些kwargs。调用函数不是问题。知道如何通过kwargs是。这是一个非工作的释义样本:

std::string message("aMessage");
boost::python::list arguments;
arguments.append("1");

boost::python::dict options;
options["source"] = "cpp";

boost::python::object python_func = get_python_func_of_wrapped_object()
python_func(message, arguments, options)

当我运用这段代码时,在pdb中我得到了(这不是我想要的):

messsage = aMessage
args = (['1'], {'source': 'cpp'})
kwargs = {}

你是怎么通过的 选项 在我的** kwargs字典中的例子?

我见过一个 岗位 建议使用**选项语法(这有多酷!):

python_func(message, arguments, **options)

不幸的是,这导致了

TypeError: No to_python (by-value) converter found for C++ type: class boost::python::detail::kwds_proxy

感谢您提供任何帮助。


11910
2018-06-28 01:49


起源



答案:


经过一些调查,结果发现对象函数调用操作符被重写为两个类型的参数 args_proxy 和 kwds_proxy。所以你必须使用这两个参数的特定调用样式。

args_proxy 和 kwds_proxy 由*重载生成。这真的很好。

另外,第一个参数必须是元组类型,以便python解释器正确处理* args参数。

结果示例有效:

boost::python::list arguments;
arguments.append("aMessage");
arguments.append("1");

boost::python::dict options;
options["source"] = "cpp";

boost::python::object python_func = get_python_func_of_wrapped_object()
python_func(*boost::python::tuple(arguments), **options)

希望这可以帮助...


14
2018-06-29 19:32



哇,我不知道*和**重载,这些微小的细节之一使boost :: python令人钦佩。 - eudoxos
请注意,即使只使用了kwargs,也需要将元组作为第一个参数。但它可以是空的: python_func(*boost::python::tuple(), **options)。 - luator


答案:


经过一些调查,结果发现对象函数调用操作符被重写为两个类型的参数 args_proxy 和 kwds_proxy。所以你必须使用这两个参数的特定调用样式。

args_proxy 和 kwds_proxy 由*重载生成。这真的很好。

另外,第一个参数必须是元组类型,以便python解释器正确处理* args参数。

结果示例有效:

boost::python::list arguments;
arguments.append("aMessage");
arguments.append("1");

boost::python::dict options;
options["source"] = "cpp";

boost::python::object python_func = get_python_func_of_wrapped_object()
python_func(*boost::python::tuple(arguments), **options)

希望这可以帮助...


14
2018-06-29 19:32



哇,我不知道*和**重载,这些微小的细节之一使boost :: python令人钦佩。 - eudoxos
请注意,即使只使用了kwargs,也需要将元组作为第一个参数。但它可以是空的: python_func(*boost::python::tuple(), **options)。 - luator