将 C 枚举导入 python 而不包括完整的 header?
Import C enum into python without including full header?
是否有一种简单的方法可以使用 SWIG 将 C header 文件中定义的枚举常量公开给 Python,但不使用 %include "header.h"
来 SWIG 整个 header ?换句话说,我正在手动编写我的 SWIG 界面,因为我不想 auto-generate python 绑定所有内容。但是,header 文件中定义了一些枚举,我希望 Python 端可以使用这些枚举。我的文件如下所示:
foo.h
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
foo.i
%module foo
%{
#include "foo.h"
%}
并且在 foo.i
中,我可以在我的 C 代码中访问 CAT
。当然,CAT
、DOG
、HORSE
在Python这边是没有的。我如何将它们暴露给 Python?
只需在 foo.i
文件中包含您想要的 foo.h
部分,而不是处理所有内容的 %include "foo.h"
:
foo.i
%module foo
%{
#include "foo.h"
%}
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
foo.h
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
typedef enum otherEnumType {
A, B, C
} otherEnum;
输出:
>>> import foo
>>> dir(foo)
['CAT', 'DOG', 'HORSE', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '_
_spec__', '__warningregistry__', '_foo', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig
_setattr', '_swig_setattr_nondynamic']
请注意 CAT/DOG/HORSE 已定义,但 A/B/C 未定义。 swig -python foo.i
生成了没有错误的包装器。
是否有一种简单的方法可以使用 SWIG 将 C header 文件中定义的枚举常量公开给 Python,但不使用 %include "header.h"
来 SWIG 整个 header ?换句话说,我正在手动编写我的 SWIG 界面,因为我不想 auto-generate python 绑定所有内容。但是,header 文件中定义了一些枚举,我希望 Python 端可以使用这些枚举。我的文件如下所示:
foo.h
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
foo.i
%module foo
%{
#include "foo.h"
%}
并且在 foo.i
中,我可以在我的 C 代码中访问 CAT
。当然,CAT
、DOG
、HORSE
在Python这边是没有的。我如何将它们暴露给 Python?
只需在 foo.i
文件中包含您想要的 foo.h
部分,而不是处理所有内容的 %include "foo.h"
:
foo.i
%module foo
%{
#include "foo.h"
%}
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
foo.h
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
typedef enum otherEnumType {
A, B, C
} otherEnum;
输出:
>>> import foo
>>> dir(foo)
['CAT', 'DOG', 'HORSE', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '_
_spec__', '__warningregistry__', '_foo', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig
_setattr', '_swig_setattr_nondynamic']
请注意 CAT/DOG/HORSE 已定义,但 A/B/C 未定义。 swig -python foo.i
生成了没有错误的包装器。