[C++-sig] Pyste Modification for operator[]: is there any python function to know whether a C++ type is a class or basic data type?
Aghera, Parixit
paghera at qualcomm.com
Wed Aug 3 10:21:13 CEST 2005
Hi All,
I have a C++ library which I want to export to python using
pyste. There are several sequence class in C++ library which overloads
[] operator and that is the only way to access an element in sequence.
Current pyste implementation (Release version 1_32_0) doesn't handle
operator [], so I modified ClassExporter.py to generate the .defs for
__getitem__ and __setitem__ in the pyste generated .cpp. Following the
template function for getitem and pyste modification. It seems that for
C++ struct/class I have to return the element by reference and for other
C++ types (basic/enums) I need to return the element by value. I learnt
this by experiments and from
boost/python/suite/indexing/vector_indexing_suite.hpp .
Now the problem I run into here is this. I need to add
return_internal_reference< 1 > in generated .def in case when getitem
function return element by reference. Now in python I don't know a way
to figure out whether IndexOp_PysteWrapper_getitem function will return
element by reference or by value, since I don't know if the return type
of operator[] is a C++ class/structure or basic data type.
Any solution/hints for solution to this problem would be a great
help.
Template Function:
template <typename T> typename boost::mpl::if_<is_class<T>,T&,T>::type
IndexOp_PysteWrapper_getitem(TAO_Unbounded_Sequence<T>& seq, int index)
{
if (index < 0) {
index = seq.length() + index; // negative index
}
if (index >= seq.length()) {
PyErr_SetString(PyExc_IndexError, "index out of range");
throw_error_already_set();
}
return seq[index];
}
Pyste Modification:
Added folloing function for handling index operator in ClassExporter.
This function is called when operator[] is found in the class being
exported. Depending on return type of the operator[] (is it const or
not), I determine whether setitem and getitem should be supported.
def HandleIndexOperator(operator):
if operator.result.const:
self.Add('inside', '.def("__getitem__",
&IndexOp_PysteWrapper_getitem<%s>)' % (operator.result.name))
else:
self.Add('inside', '.def("__setitem__",
&IndexOp_PysteWrapper_setitem<%s>)' % (operator.result.name))
Thanks,
Parixit
More information about the Cplusplus-sig
mailing list