How to use enum in swig using python?

I have an enumeration declaration as follows:

typedef enum mail_ { Out = 0, Int = 1, Spam = 2 } mail; 

Functions:

 mail status; int fill_mail_data(int i, &status); 

In the above function, status populated and sent.

When I try to do this through swig, I encounter the following problems:

  • It does not show mail details. When I try to print mail.__doc__ or help(mail) , it throws an error saying that there is no such attribute, although I can use these values ​​( Spam , In and Out ).
  • As shown above, Swig does not know what main , so it does not accept any function arguments for this mail .
+6
source share
1 answer

For SWIG, enum is an integer. To use it as an output parameter, as in your example, you can also declare the parameter as an output parameter as follows:

 %module x // Declare "mail* status" as an output parameter. // It will be returned along with the return value of a function // as a tuple if necessary, and will not be required as a function // parameter. %include <typemaps.i> %apply int *OUTPUT {mail* status}; %inline %{ typedef enum mail_ { Out = 0, Int = 1, Spam = 2 } mail; int fill_mail_data(int i, mail* status) { *status = Spam; return i+1; } %} 

Using:

 >>> import x >>> dir(x) # Note no "mail" object, just Int, Out, Spam which are ints. ['Int', 'Out', 'Spam', '__builtins__', '__cached__', '__doc__', '__file__', '__initializing__', '__loader__', '__name__', '__package__', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic', '_x', 'fill_mail_data'] >>> x.fill_mail_data(5) [6, 2] >>> ret,mail = x.fill_mail_data(5) >>> mail == x.Spam True 
+5
source

Source: https://habr.com/ru/post/958398/


All Articles