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

I want to embed a function written in python in C ++ code.
My python code: test.py

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

My C ++ code:

 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? 
+6
source share
2 answers

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

Here is a prototype 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 converting the return value from PyObject_Call to the formal boost::python::object you can either return it from your function or just forget about it, and the new link returned by PyObject_Call will be automatically deleted.

For more information on wrapping PyObject* as boost::python::object see the Boost.Python manual. More precisely, at this link the end of the page .

+1
source

theoretical answer (no time to try yourself: - |):

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

Source: https://habr.com/ru/post/892242/


All Articles