使用 Swig 将 C 枚举包装在 Python 模块中 [英] Wrapping C-enum in a Python module with Swig

查看:42
本文介绍了使用 Swig 将 C 枚举包装在 Python 模块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 myenum.h 中有一个简单的 C 枚举:

enum MyEnum {一,二,三};

问题是,当我将其映射到 Python 时,我只能通过模块名称访问枚举,而不能通过 MyEnum.因此,值 ONE、TWO、THREE 包含在我定义的任何其他函数中,而不是包含在 MyEnum 中.

我的 api.i 文件是:

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

我用 SWIG 生成

swig -builtin -python api.i

并导入到Python中

import _api

现在我必须使用 _api 模块中的枚举值:

_api.ONE_api.TWO_api.三

虽然我想像这样使用它们

_api.MyEnum.ONE_api.MyEnum.TWO_api.MyEnum.THREE

有谁知道我如何才能做到这一点?

解决方案

有一个 SWIG 功能 nspace 这确实是您想要的,但不幸的是 Python 尚不支持它.我总是不得不在结构中定义枚举,以便它以您希望的方式在 SWIG 中显示.示例:

%module tmp%排队 %{结构我的枚举{枚举 { A,B,C };};%}

结果:

<预><代码>>>>导入tmp>>>tmp.MyEnum.A0>>>tmp.MyEnum.B1>>>tmp.MyEnum.C2

I have a simple enum in C in myenum.h:

enum MyEnum {
    ONE,
    TWO,
    THREE
};

The problem is that when I map this to Python, I can only access the enum through the module name, not through MyEnum. So the values ONE, TWO, THREE are included with any other functions I define, instead of being contained with MyEnum.

My api.i file is:

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

I generate with SWIG

swig -builtin -python api.i

And import it into Python

import _api

And now I have to use the enum values from the _api module:

_api.ONE
_api.TWO
_api.THREE

While I want to use them like

_api.MyEnum.ONE
_api.MyEnum.TWO
_api.MyEnum.THREE

Does anyone know how I can accomplish this?

解决方案

There is a SWIG feature nspace that would do want you want, but unfortunately it isn't supported for Python yet. I've always had to define the enum in a struct for it to show up in the manner you desire in SWIG. Example:

%module tmp

%inline %{
struct MyEnum {
    enum { A,B,C };
};
%}

Result:

>>> import tmp
>>> tmp.MyEnum.A
0
>>> tmp.MyEnum.B
1
>>> tmp.MyEnum.C
2

这篇关于使用 Swig 将 C 枚举包装在 Python 模块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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