python - 如何在 python 中使用枚举?

标签 python enums swig

我有一个枚举声明如下:

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

功能:

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

在上面的函数中,status 被填满并发送。

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

  1. 它没有显示邮件 的详细信息。当我尝试打印 mail.__doc__help(mail) 时,它会抛出一个错误,指出没有这样的属性,尽管我能够使用这些值( 垃圾邮件InOut)。
  2. 如上所示,Swig 不知道 main 是什么,因此它不接受该 mail 的任何函数参数。

最佳答案

对于 SWIG,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;
}

%}

使用:

>>> 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

关于python - 如何在 python 中使用枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20073674/

相关文章:

python - 单元测试使用 Mock 4.0.0 生成 "RuntimeError: Working outside of application context."

C 程序——在编译时检查两个枚举是否同步

lua - Swig 类型转换为派生类?

c# - 将非托管 unicode 字符串编码到 .net。高字符替换为问号

python - Python 中的 8 Queens 解决方案

python - Spyder IDE 中的重复日志条目和锁定的日志文件

python - 我无法安装Opencv

c# - 如何在 C# 中 DllImport 枚举

c# - 如何让接口(interface)中的 C# 枚举像 C 一样?

python - 通过引用传递的 SWIG Python 固定大小数组