[C++-sig] Howto wrap operator[]? (boost::python)
Nicodemus
nicodemus at globalite.com.br
Fri Jun 13 23:19:29 CEST 2003
Neal D. Becker wrote:
>I am playing with exposing std::vector<double>. So far I got init OK, now I
>want to expose operator[]. I don't see anything in the tutorial about
>this. Any hints?
>
>
>
Currently you will have to expose them by hand. Python has two especial
methods, named __setitem__ and __getitem__, that allows a class to
define the behaviour of the [] operator. All you have to do is export
this especial methods as members of your class. Here is some code
(untested):
template <class T>
void vector_setitem(std::vector<T>& v, int index, T value)
{
if (index >= 0 && index < v.size()) {
v[index] = value;
}
else {
PyErr_SetString(PyExc_IndexError, "index out of range");
throw_error_already_set();
}
}
template <class T>
T vector_getitem(std::vector<T> &v, int index)
{
if (index >= 0 && index < v.size()) {
return v[index];
}
else {
PyErr_SetString(PyExc_IndexError, "index out of range");
throw_error_already_set();
}
}
BOOST_PYTHON_MODULE(std)
{
class_<std::vector<double> >(...)
...
.def("__getitem__", &vector_getitem)
.def("__setitem__", &vector_setitem)
;
}
More information about the Cplusplus-sig
mailing list