如何在boost.python中指定命名参数的值? [英] How can I specify the value of a named argument in boost.python?
问题描述
我想将python编写的函数嵌入到c ++代码中.
我的python代码是:test.py
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
我的c ++代码是:
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?
推荐答案
我不确定Boost.Python是否实现了声明的**
解除引用运算符,但是您仍然可以使用Python C-API执行您所使用的方法如此处所述进行.
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.
这是解决方案的原型:
//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));
将返回值从PyObject_Call
转换为正式的boost::python::object
之后,您可以从函数中返回它,也可以忘了它,并且PyObject_Call
返回的新引用将被自动删除.
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.
有关将PyObject*
包装为boost::python::object
的更多信息,请参阅Boost.Python教程. 更精确地说,链接,页面的结尾.
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.
这篇关于如何在boost.python中指定命名参数的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!