Jago Jago - 3 years ago 54
C++ Question

The same enumeration items wraps in a constants of different types in SWIG > 2.0.1

I find a little bug in SWIG 3.0.12. If you make little changes in file examples/python/enum/example.h, just add a char constant to the one of enum item (g):

enum color { RED, BLUE, GREEN = 'g'};

And then make a wrap, compile _example.so and run
$python runme.py
, you will get:

enter code here

*** color ***
RED = 0
BLUE = 1

*** Foo::speed ***
Foo_WARP = 1

Testing use of enums with functions

color = RED, speed = IMPULSE speed
color = BLUE, speed = WARP speed
Traceback (most recent call last):
File "runme.py", line 22, in <module>
example.enum_test(example.GREEN, example.Foo.LUDICROUS)
TypeError: in method 'enum_test', argument 1 of type 'color'

It is strange situation, isn't it? The same enumeration items wraps in a constants of different types and the poor little function waits just one type of enum constant (now it waits ints, but GREEN constant type is char). How it can be bypassed without rollback SWIG version, what do you think?

This bug appears in SWIG 3.0.12, 3.0.11, but in 2.0.1 all works fine.

Answer Source

Ok, it's an old SWIG bug which appears 6 years earlier, when SWIG developers add Different-Type-Enums feature. May be they forgot about dynamically typed languages such as PHP and Python, I don't know, but for me this problem resolved by compile my own SWIG build with changes in the parser source code...

Just add the if-condition at Source/CParse/parser.y after:

5620 5620 Swig_error(cparse_file,cparse_line,"Type error. Expecting an integral type\n"); 
5621 5621 } 
5622 -    if ($$.type == T_CHAR) $$.type = T_INT; 
5623 5622 } 
5624 5623 ;

Then build your own SWIG with this little change and you will get wrapping all enums items to integer constants.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download