该boost/python/args.hpp
文件提供了一系列用于指定参数关键字的类。特别是,Boost.Python 提供了一个arg
类型,它代表一个潜在的关键字参数。它重载了逗号运算符以允许对参数列表进行更自然的定义。
暴露myFunction
在MyClass
as my_function
、 where a
、b
和c
是关键字参数,并且c
具有默认值0
可以写成如下:
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<MyClass>("MyClass")
.def("my_function", &MyClass::myFunction,
(python::arg("a"), "b", python::arg("c")=0))
;
}
这是一个完整的例子:
#include <boost/python.hpp>
class MyClass
{
public:
double myFunction(int a, int b, int c)
{
return a + b + c;
}
};
BOOST_PYTHON_MODULE(example)
{
namespace python = boost::python;
python::class_<MyClass>("MyClass")
.def("my_function", &MyClass::myFunction,
(python::arg("a"), "b", python::arg("c")=0))
;
}
互动使用:
>>> import example
>>> my_class = example.MyClass()
>>> my_class.my_function(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
MyClass.my_function(MyClass, int)
did not match C++ signature:
my_function(MyClass {lvalue}, int a, int b, int c=0)
>>> assert(5 == my_class.my_function(2, 3))
>>> assert(6 == my_class.my_function(2, 3, 1))
>>> my_class.my_function(2, 3, 1, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
MyClass.my_function(MyClass, int, int, int, int)
did not match C++ signature:
my_function(MyClass {lvalue}, int a, int b, int c=0)
>>> assert(6 == my_class.my_function(3, 1, c=2))
>>> assert(7 == my_class.my_function(a=2, b=2, c=3))
>>> my_class.my_function(b=2, c=1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Boost.Python.ArgumentError: Python argument types in
MyClass.my_function(MyClass)
did not match C++ signature:
my_function(MyClass {lvalue}, int a, int b, int c=0)