[C++-sig] enums and structs
David Abrahams
david.abrahams at rcn.com
Sun May 19 17:39:14 CEST 2002
----- Original Message -----
From: "Achim Domma" <achim.domma at syynx.de>
> > -----Original Message-----
> > > in Daves progress report from march he mentioned a new interface
> > > for exposing enums.
> >
> > Yes, as described in
> > http://mail.python.org/pipermail/c++-sig/2002-April/000907.html
> >
> >
> > > Is the code above the right one
> >
> > No, the above is a v1 interface.
> >
> > > or will the
> > > interface change in V2 ?
> >
> > The link tells all.
>
> I don't understand which way I should go at the moment. The interface for
V2
> looks nice, but as far as I can see, it's not implemented yet. Trying to
use
> 'enum_as_int_converters' I get the following errors (not surprising me,
if
> I mix to implementations) :
Right, not surprising.
> > You can always use the following until we get the nice interface:
> >
> > module("my_module")
> > .setattr("enum_value_1", PyInt_FromLong(enum_value_1))
>
> I understand. This expose only the the enum-values, but how do I enable
> enum<->int conversion? Should I implement to_python/from_python for all
my
> enums?
Uhh... well, I guess that's what you'd need to do, until the new interface
is implemented. However, it's pretty easy to get the from_python converters
(http://www.boost.org/libs/python/doc/v2/implicit.html):
implicitly_convertible<int, my_enum_type>();
As for the to_python converters,
// use with to_python_converter
// http://www.boost.org/libs/python/doc/v2/to_python_converter.html
template <class T>
struct enum_to_int_converter
{
static PyObject* convert(T const& x)
{
return PyInt_FromLong(x);
}
};
Putting it together:
template <class T>
void enum_as_int(T* = 0)
{
to_python_converter<T,enum_to_int_converter<T> >();
implicitly_convertible<int, my_enum_type>();
}
Now:
enum_as_int<my_enum_type>();
> > > It would be no problem to make a copy of the string
> > > passed from python, but how/when will this copy be destroyed ?
> >
> > I don't understand what you mean, sorry. Are you concerned about how to
> > *construct* these structs, or is it something else?
>
> If I have something like
>
> struct {
> char * member;
> } myStruct;
>
> and then try to do something like
>
> class_<myStruct>("myStruct")
> .def_readwrite("member",&myStruct::member);
>
> would it work? I could not imagine how memory management of the string
> should work.
I suggest that you expose a class derived from myStruct which handles the
memory management, then use the property facility described in
http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/*checkout*/boost/boost/libs/
python/doc/v2/class.html?rev=HEAD&content-type=text/html#class_-spec-modifi
ers to get write access to the data from Python.
-Dave
More information about the Cplusplus-sig
mailing list