Wrapping C-enum in a Python module using Swig

I have a simple listing 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 enumeration through the module name, not through MyEnum. So the ONE, TWO, THREE values ​​are included in any other functions that I define, instead of containing MyEnum.

My api.i file:

 %module api %{ #include "myenum.h" %} %include "myenum.h" 

I generate using SWIG

 swig -builtin -python api.i 

And import it in Python

 import _api 

And now I have to use the enum values ​​from the _api module:

 _api.ONE _api.TWO _api.THREE 

While I want to use them as

 _api.MyEnum.ONE _api.MyEnum.TWO _api.MyEnum.THREE 

Does anyone know how I can do this?

+8
c python swig
source share
2 answers

There is a SWIG nspace function that you would like to, but, unfortunately, it is not supported for Python yet. I have always had to define an enumeration in a structure so that it appears the way you want in SWIG. Example:

 %module tmp %inline %{ struct MyEnum { enum { A,B,C }; }; %} 

Result:

 >>> import tmp >>> tmp.MyEnum.A 0 >>> tmp.MyEnum.B 1 >>> tmp.MyEnum.C 2 
+1
source share

What you need to understand is that in C, these names in your enumeration do not take up space, as they would in Python. You should probably read something about how enums can be used before continuing.

Now note that since they are globally accessible names, they will not be hosted in Python. It is best to create an object in the following lines:

 class MyEnum: A = A B = B C = C del(A, B, C) 

Then A, B, C will be available only through _api.MyEnum.A etc., and A, B, C will not be available directly.

+1
source share

All Articles