如何在 boost.python 中指定命名参数的值?
我想将用 python 编写的函数嵌入到 c++ 代码中。
我的Python代码是: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?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不确定 Boost.Python 是否实现了所声称的
**
解引用运算符,但您仍然可以使用 Python C-API 来执行您正在测试的方法,如此处所述。以下是解决方案的原型:
将返回值从
PyObject_Call
转换为正式的boost::python::object
后,您可以从函数中返回它或者您可以忘记它,PyObject_Call
返回的新引用将被自动删除。有关将
PyObject*
包装为boost::python::object
的更多信息,请参阅 Boost.Python 教程。 更准确地说,在此链接,页面末尾。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:
After you have converted the return value from
PyObject_Call
to a formalboost::python::object
, you can either return it from your function or you can just forget it and the new reference returned byPyObject_Call
will be auto-deleted.For more information about wrapping
PyObject*
asboost::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 :-| ):