如何在python中使用枚举?

Kau*_*eru 6 python enums swig

我有一个枚举声明如下:

typedef enum mail_ {
 Out = 0,
 Int = 1,
 Spam = 2
} mail;
Run Code Online (Sandbox Code Playgroud)

功能:

mail status;
int fill_mail_data(int i, &status);
Run Code Online (Sandbox Code Playgroud)

在上面的函数中,status填充并将发送.

当我通过swig尝试这个时,我面临以下问题:

  1. 它没有显示细节mail.当我尝试打印mail.__doc__ 或者help(mail),它抛出一个错误,说没有这样的属性,虽然我虽然能够使用这些值(Spam,In,和Out).
  2. 如上所示,Swig不知道是什么main,所以它不接受任何函数参数mail.

Mar*_*nen 5

对于SWIG,a enum只是一个整数.要将它用作示例中的输出参数,您还可以将参数声明为输出参数,如下所示:

%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;
}

%}
Run Code Online (Sandbox Code Playgroud)

使用:

>>> 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
Run Code Online (Sandbox Code Playgroud)