How can I specify the value of a named argument in boost.python?

情到浓时终转凉″ 提交于 2019-12-07 02:36:58

问题


i want to embed a function written in python into c++ code.
My python code is:test.py

def func(x=None, y=None, z=None):  
  print x,y,z  

My c++ code is:

module = import("test");  
namespace = module.attr("__dict__");  

//then i want to know how to pass value 'y' only.  
module.attr("func")("y=1") // is that right?

回答1:


I'm not sure Boost.Python implements the ** dereference operator as claimed, but you can still use the Python C-API to execute the method you are intested on, as described here.

Here is a prototype of the solution:

//I'm starting from where you should change
boost::python::object callable = module.attr("func");

//Build your keyword argument dictionary using boost.python
boost::python::dict kw;
kw["x"] = 1;
kw["y"] = 3.14;
kw["z"] = "hello, world!";

//Note: This will return a **new** reference
PyObject* c_retval = PyObject_Call(callable.ptr(), NULL, kw.ptr());

//Converts a new (C) reference to a formal boost::python::object
boost::python::object retval(boost::python::handle<>(c_retval));

After you have converted the return value from PyObject_Call to a formal boost::python::object, you can either return it from your function or you can just forget it and the new reference returned by PyObject_Call will be auto-deleted.

For more information about wrapping PyObject* as boost::python::object, have a look at the Boost.Python tutorial. More precisely, at this link, end of the page.




回答2:


a theoretical answer (no time to try myself :-| ):

boost::python::dict kw;
kw["y"]=1;
module.attr("func")(**kw); 


来源:https://stackoverflow.com/questions/6612261/how-can-i-specify-the-value-of-a-named-argument-in-boost-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!