17

我有一个带有这个签名的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 字典中传递我的示例中的选项?

我看到一篇帖子建议使用 **options 语法(这太酷了!):

python_func(message, arguments, **options)

不幸的是,这导致

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

感谢您提供的任何帮助。

4

1 回答 1

20

经过一番调查,事实证明对象函数调用运算符被两个类型的参数覆盖args_proxykwds_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)

希望这可以帮助...

于 2011-06-29T19:32:54.630 回答