Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

boost-python

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?
like image 890
yelo Avatar asked Jul 07 '11 14:07

yelo


1 Answers

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.

like image 92
André Anjos Avatar answered Jan 02 '23 12:01

André Anjos