how to use enum in swig with python?

蓝咒 提交于 2019-12-08 21:33:29

问题


I have a enum declaration as follows:

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

Function:

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

In the function above, status gets filled up and will send.

When I am trying this through swig I am facing the following issues:

  1. It is not showing details of mail. When I try to print mail.__doc__ or help(mail), it is throwing an error saying there is no such Attribute, though though i am able to use those values (Spam, In, and Out).
  2. As shown above, the Swig does not know what main is, so it is not accepting any function arguments for that mail.

回答1:


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

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

%}

Use:

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


来源:https://stackoverflow.com/questions/20073674/how-to-use-enum-in-swig-with-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!