[C++-sig] Overloaded [] operator

Nicodemus nicodemus at esss.com.br
Tue Jul 19 13:28:10 CEST 2005


For some sample code (untested):

Octet& MyClass__getitem__(MyClass& c, ULong p)
{
    if (p < 0) {
       p = c.size() + p; // negative index
    }
    if (p > c.size()-1) {
        PyErr_SetString( PyExc_IndexError, "index out of range" 
);                                            
        boost::python::throw_error_already_set();   
    }
    return c[p];
}


BOOST_PYTHON_MODULE(mymodule)
{
   class_<MyClass, ...>(...)
      .def( "__getitem__", &MyClass__getitem__)
   ;
}

__setitem__ should be similar.

HTH,
Nicodemus.


Nick Rasmussen wrote:

>you can overload "__getitem__" and "__setitem__" for the [] operator.
>
>-nick
>
>On Mon, 18 Jul 2005, Ram, Siddharth wrote:
>
>  
>
>>I have a C++ class which defines the following method:
>>
>>CORBA::Octet &operator[] (CORBA::ULong);
>>
>>I am trying to figure out how to export this to python using
>>pyste/Boost.Python.
>>http://www.boost.org/libs/python/doc/v2/operators.html does not include
>>the square bracket operator in the list of operators. Is this not a
>>supported operation ? How do I specify a  python method which would
>>result in this method being invoked in C++ ?
>>
>>Thanks
>>Siddharth
>>_______________________________________________
>>C++-sig mailing list
>>C++-sig at python.org
>>http://mail.python.org/mailman/listinfo/c++-sig
>>    
>>
>
>_______________________________________________
>C++-sig mailing list
>C++-sig at python.org
>http://mail.python.org/mailman/listinfo/c++-sig
>
>  
>



More information about the Cplusplus-sig mailing list