如何在Boost.Python暴露类方法时使用预定义输入参数
使用Boost.Python为C++类实现带固定参数的属性访问
要复用GetValue方法,同时在Python中以属性形式访问数组元素,你可以借助boost::bind或者Boost.Python的lambda绑定功能,给每个属性指定固定的索引参数,具体实现如下:
方法一:使用boost::bind绑定固定索引
引入<boost/bind.hpp>头文件,通过boost::bind将GetValue成员函数与固定索引绑定,生成适配add_property要求的可调用对象:
#include <boost/python.hpp> #include <boost/bind.hpp> class MyClass { private: int myArray[3] = {100, 200, 300}; public: int GetValue(int index) {return myArray[index];} }; BOOST_PYTHON_MODULE(MyModule) { using namespace boost::python; class_<MyClass>("MyClass") // _1代表MyClass实例本身,对应成员函数的this指针 .add_property("first", boost::bind(&MyClass::GetValue, _1, 0)) .add_property("second", boost::bind(&MyClass::GetValue, _1, 1)) .add_property("third", boost::bind(&MyClass::GetValue, _1, 2)) ; }
方法二:使用Boost.Python lambda表达式
如果你的Boost版本支持Python lambda模块,可以用lambda命名空间下的bind完成同样操作,代码更简洁:
#include <boost/python.hpp> #include <boost/python/lambda.hpp> class MyClass { private: int myArray[3] = {100, 200, 300}; public: int GetValue(int index) {return myArray[index];} }; BOOST_PYTHON_MODULE(MyModule) { using namespace boost::python; using namespace boost::python::lambda; class_<MyClass>("MyClass") .add_property("first", bind(&MyClass::GetValue, _1, 0)) .add_property("second", bind(&MyClass::GetValue, _1, 1)) .add_property("third", bind(&MyClass::GetValue, _1, 2)) ; }
效果验证
编译生成模块后,在Python中即可按预期访问属性:
import MyModule my_class = MyModule.MyClass() print(my_class.first) # 输出100 print(my_class.second) # 输出200 print(my_class.third) # 输出300
注意事项
- 编译时需确保链接Boost.Python和Boost.Bind库(方法一),或Boost.Python lambda模块(方法二)
- 若
MyClass定义在单独头文件中,记得引入对应头文件
内容的提问来源于stack exchange,提问作者rrsszzcc
相关产品推荐
相关产品推荐

