Embedded Boost.Python Enum

Cory Cory.Leach at gmail.com
Fri Oct 19 01:40:43 CEST 2007


Ok, I finally got it figured out. The secret which no one told me what
that if you're doing embedding, you have to initialize your modules!

BOOST_PYTHON_MODULE(Enums){ ... } defines the function initEnums()
which must be called before you can import the module. Finally figured
it out by looking here: http://members.gamedev.net/sicrane/articles/EmbeddingPythonPart1.html

It's odd to me that little tidbit got left out of the boost.python
tutorial page on embedding... I must have looked at it 100 times.


On Oct 18, 12:59 am, Cory <Cory.Le... at gmail.com> wrote:
> Hi,
>
> I have a hopefully quick question about how to use Boost.Python to
> export an Enum.
> I am embedding python in C++ and am currently exporting my classes in
> the following way:
>
> nameSpace["OBJECT"] = class_<OBJECT>("OBJECT")
>         .def("getType", &OBJECT::getType)
>         .def("setSprite", &OBJECT::setSprite);
>
> So following this, I assumed that when exporting an enum the following
> should work:
>
> nameSpace["OBJECT_TYPE"] = enum_<OBJECT_TYPE>("OBJECT_TYPE")
>                         .value("GENERIC_OBJECT",GENERIC_OBJECT)
>                         .value("MAP_OBJECT",MAP_OBJECT)
>                         .value("TOTAL_OBJECT_TYPES",TOTAL_OBJECT_TYPES)
>                         .export_values();
>
> while the above compiles, it causes the following run time exception:
>
> AttributeError: 'NoneType' object has no attribute 'OBJECT_TYPE'
>
> I took a look at the documentation and the only explanation I found
> for enum appeared to be for extending python with modules. using the
> following form:
>
> BOOST_PYTHON_MODULE(enums)
> {
>     enum_<color>("color")
>         .value("red", red)
>         .value("green", green)
>         .export_values()
>         .value("blue", blue)
>         ;
>
> }
>
> I COULD do the above, I would prefer the first method if possible. I
> however do not know how to import the module if it is statically
> linked because doing a simple import does not work and I am not
> familiar enough with the boost.python library, Python C API, or Python
> itself to know how to set it up. So My question is this:
>
> How can I either make the first method of adding an enum work and not
> throw the exception, OR once I create the BOOST_PYTHON_MODULE in an
> embedded python c++ program how to I then import that module into my
> embedded python?
>
> Thanks in advance for any help
>
> -Cory





More information about the Python-list mailing list