SWIG-将C ++枚举转换为Python枚举 [英] SWIG- Convert C++ enum to Python enum

查看:95
本文介绍了SWIG-将C ++枚举转换为Python枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用swig将C ++类枚举转换为python枚举。我在example.h文件中具有以下实现。

I am working to get C++ class enum to python enum using swig. I have the following implementation in example.h file.

namespace colors{ 
 enum class Color{
    RED = 0,
    BLUE = 1,
    GREEN = 2
 };
}

我的Swig界面文件为

My Swig interface file is

    %module api
%{
#include "example.h"
%}
%include "example.h"

但是使用swig工具后,界面提供了以下用法

But after using swig tool the interface provides the following usage

import pywarp_example as impl 
impl.RED

这里出现的问题是,是否可以像下面这样访问enum,这就是我们在python中使用的方式?

The question arise here is that is it possible to access enum like below thats the way we use in python?

impl.Color.RED Or impl.Color.RED.value


推荐答案

不同于您的示例,SWIG 3.0.12会将您的枚举类的示例包装为 Color_RED Color_BLUE Color_GREEN 。这是一个示例,其中添加了一些其他Python代码以将该模式重新映射到 Color.RED Color.BLUE Color.GREEN

Unlike your example SWIG 3.0.12 would wrap your enum class example as Color_RED, Color_BLUE, and Color_GREEN. Here's an example that adds some additional Python code to remap that pattern into Color.RED, Color.BLUE, and Color.GREEN:

%pythoncode 已添加到SWIG包装程序的Python部分。在Python扩展加载后,此代码将运行。它会收集和删除以 prefix _ 开头的变量,将其重命名为不包含 prefix _ ,然后创建一个名为的类。 前缀 ,并将新变量作为类变量。

%pythoncode is added to the Python portion of the SWIG wrapper. After the Python extension loads this code runs. It collects and deletes variables starting with prefix_, renames them without prefix_, then creates a class named prefix with the new variables as class variables.

%module test

%inline %{
namespace colors{ 
 enum class Color{
    RED = 0,
    BLUE = 1,
    GREEN = 2
 };
}
%}

%pythoncode %{
from enum import Enum
def redo(prefix):
    tmpD = {k:v for k,v in globals().items() if k.startswith(prefix + '_')}
    for k,v in tmpD.items():
        del globals()[k]
    tmpD = {k[len(prefix)+1:]:v for k,v in tmpD.items()}
    # globals()[prefix] = type(prefix,(),tmpD) # pre-Enum support
    globals()[prefix] = Enum(prefix,tmpD)
redo('Color')
del redo  # cleaning up the namespace
del Enum
%}

示例用法:

>>> import test
>>> dir(test)
['Color', '__builtin__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig_setattr', '_swig_setattr_nondynamic', '_test']
>>> test.Color
<enum 'Color'>
>>> dir(test.Color)
['BLUE', 'GREEN', 'RED', '__class__', '__doc__', '__members__', '__module__']
>>> test.Color.BLUE
<Color.BLUE: 1>

这篇关于SWIG-将C ++枚举转换为Python枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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