SWIG- Convert C++ enum to Python enum

感情迁移 提交于 2019-12-10 16:02:01

问题


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

My Swig interface file is

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

But after using swig tool the interface provides the following usage

import pywarp_example as impl 
impl.RED

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

回答1:


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

Example use:

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



回答2:


C++ Enum can be converted to python Enum using this script.

%pythoncode %{
from enum import Enum
def enum(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] = Enum(prefix,tmpD)
%}


来源:https://stackoverflow.com/questions/50353506/swig-convert-c-enum-to-python-enum

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