i want to embed a function written in python into c++ code.
My python code is:test.pydef 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?
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.
a theoretical answer (no time to try myself :-| ):
boost::python::dict kw;
kw["y"]=1;
module.attr("func")(**kw);
精彩评论