Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

keyword argument - How do you pass kwargs to a boost-python wrapped function?

I have a python function with this signature:

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

I would like to call the function from c++ and pass to it some kwargs. Calling the function is not the problem. Knowing how to pass the kwargs is. Here is a non-working paraphrased sample:

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)

When I exercise this code, in pdb I get (which is not what I would like):

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

How do you pass the options in my example in the **kwargs dictionary ?

I have seen one post suggesting to use the **options syntax (how cool is this!):

python_func(message, arguments, **options)

Unfortunately, this results in

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

Thank you for any help you can give.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After some investigation, it turns out that the object function call operator is overridden for two arguments of type args_proxy and kwds_proxy. So you have to use this specific call style of two arguments.

args_proxy and kwds_proxy are generated by the * overloads. This is really nice.

Additionally, the first argument must be a tuple type so that the python interpreter correctly handles the *args argument.

The resulting example works:

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)

Hope this helps...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...