Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping C-enum in a Python module with Swig

Tags:

python

c

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 name, not through MyEnum. So the values ONE, TWO, THREE are included with any other functions I define, instead of being contained with MyEnum.

My api.i file is:

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

I generate with SWIG

swig -builtin -python api.i

And import it into 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 like

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

Does anyone know how I can accomplish this?

like image 481
mindvirus Avatar asked May 09 '13 21:05

mindvirus


1 Answers

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 %{
struct MyEnum {
    enum { A,B,C };
};
%}

Result:

>>> import tmp
>>> tmp.MyEnum.A
0
>>> tmp.MyEnum.B
1
>>> tmp.MyEnum.C
2
like image 195
Mark Tolonen Avatar answered Nov 15 '22 15:11

Mark Tolonen