Skip to content Skip to sidebar Skip to footer

Wrapping C-enum In A Python Module With Swig

I have a simple enum in C in myenum.h: enum MyEnum { ONE, TWO, THREE }; The problem is that when I map this to Python, I can only access the enum through the module na

Solution 1:

There is a SWIG feature nspace that would do want you want, but unfortunately it isn't supported for Python yet. I've always had to define the enum in a struct for it to show up in the manner you desire in SWIG. Example:

%module tmp

%inline %{
structMyEnum {
    enum { A,B,C };
};
%}

Result:

>>>import tmp>>>tmp.MyEnum.A
0
>>>tmp.MyEnum.B
1
>>>tmp.MyEnum.C
2

Solution 2:

What you need to understand is that in C those names in your enum are not namespaced as they would be in Python. You should probably read something about how enums can be used before continuing.

Now note that since those are globally accessible names, they will not be namespaced in Python. Your best bet, is to create an object, along these lines:

classMyEnum:
   A = AB=BC= C

del(A, B, C)

Then A, B, C will only be accessible through _api.MyEnum.A, etc., and A, B, C won't be directly accessible.

Post a Comment for "Wrapping C-enum In A Python Module With Swig"