如何使用SWIG枚举枚举成员 [英] How to enumerate enum members using SWIG

查看:427
本文介绍了如何使用SWIG枚举枚举成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将一个C ++ enum 暴露给SWIG作为一个真实的实体,而不是一组常量,所以我可以在python代码中枚举它们?

Can I expose a C++ enum to SWIG as a real entity rather than a set of constants so I can enumerate over them in python code?

推荐答案

我遇到了同样的问题。我希望SWIG很快支持C ++ 11的枚举类

I faced the same issue. I hope that SWIG soon supports C++11's enum class.

这里有一个黑客说服SWIG在结构中:

Here's a hack that convinces SWIG to put enums in a structure:

#ifdef SWIG
%rename(MyEnum) MyEnumNS;
#endif

struct MyEnumNS
{
    enum Value { Value1, Value2, Value3 };
};
typedef MyEnumNS::Value MyEnum;

.cpp MyEnum :: Value1 ,在Python代码中它是 MyEnum.Value1 。虽然令人费解,但 typedef 可防止必须更改使用枚举的现有代码,SWIG%rename使SWIG包装器中的枚举具有相同的名称。

In .cpp code you now must use MyEnum::Value1 and in Python code it is MyEnum.Value1. Although convoluted, the typedef prevents having to change existing code that uses the enum everywhere and the SWIG %rename makes the enum have the same name in the SWIG wrapper.

在Python中,您可以使用一些代码枚举值:

In Python you can enumerate the values with a little code:

def values(enum):
    return [(k,v) for k,v in vars(enum).items() if isinstance(v,int)]

这不漂亮,我很想看到更好的解决方案。

It's not pretty, and I'd love to see a better solution.

这篇关于如何使用SWIG枚举枚举成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆