I am trying to expose a C++ class to Python using Boost Python Library. I have a class with an array of 3 elements and I wish to be able to get the value of element by the names of "first", "second", "third". Since the array is private, I wrote a getter function taking the index as input and return the value of the element.
class MyClass {
private:
int myArray[3] = {100, 200, 300};
public:
int GetValue(int index) {return myArray[index];}
};
I wish to be able to use this class in Python as follows:
my_class = MyClass()
print(my_class.first)
print(my_class.second)
print(my_class.third)
''' results:
100
200
300
'''
Here is how I tried to expose this class:
BOOST_PYTHON_MODULE(MyModule) {
using namespace boost::python;
class_<MyClass>("MyClass")
.add_property("first", &MyClass::GetValue) // I want to pass 0 as index in this case
.add_property("second", &MyClass::GetValue) // I want to pass 1 as index in this case
.add_property("third", &MyClass::GetValue) // I want to pass 2 as index in this case
;
However, I don't know how and if I can specify a pre-defined input when exposing a function. I could define 3 different getter functions which return different element, but I want to reuse a same getter. Also, I used add_property() instead of def() because I want to access via MyClass.first, not MyClass.first() Any help/suggestions greatly appreciated :)
I think you can specify this like, i know you can do this with .def, nut sure with properties