Wrapping enums
Because there is in general no way to deduce that a value of arbitrary type T
is an enumeration constant, py_cpp cannot automatically convert enum values to
and from Python. To handle this case, you need to decide how you want the enum
to show up in Python (since Python doesn't have enums). If you are satisfied
with a Python int as a way to represent your enum values, you can write some
simple from_python() and to_python() functions in
namespace py::
#ifndef PY_NO_INLINE_FRIENDS_IN_NAMESPACE // workaround GCC 2.95.2 bug
namespace py {
#endif
MyEnumType from_python(PyObject* x,
py::Type<MyEnumType>)
{
return static_cast<MyEnum>(
from_python(x, py::Type<long>()));
}
PyObject* to_python(MyEnumType x)
{
return to_python(static_cast<long>(x));
}
#ifndef PY_NO_INLINE_FRIENDS_IN_NAMESPACE
}
#endif
This technique defines the conversions of
MyEnumType in terms of the conversions for the built-in
long type.
You may also want to add a bunch of lines like this to your module
initialization:
You can also add these to an extension class definition:mymodule.add(py::to_python(enum_value_1), "enum_value_1"); mymodule.add(py::to_python(enum_value_2), "enum_value_2"); ...
my_class.add(py::to_python(enum_value_1), "enum_value_1"); my_class.add(py::to_python(enum_value_2), "enum_value_2"); ...
© Copyright David Abrahams 2000. Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.
Updated: Nov 5, 2000