是否将C enum导入python而不包含完整的头文件?
是否有一种简单的方法可以使用SWIG将C头文件中定义的枚举常量公开给Python,但不使用是否将C enum导入python而不包含完整的头文件?,python,c,enums,swig,Python,C,Enums,Swig,是否有一种简单的方法可以使用SWIG将C头文件中定义的枚举常量公开给Python,但不使用%include“header.h”来SWIG整个头文件?换句话说,我正在手动编写SWIG接口,因为我不想为所有内容自动生成python绑定。但是,在头文件中定义了一些枚举,我想让Python端可以使用这些枚举。我的文件如下所示: foo.h typedef enum fooEnumType { CAT, DOG, HORSE } fooEnum; typedef enum fooEnumType
%include“header.h”
来SWIG整个头文件?换句话说,我正在手动编写SWIG接口,因为我不想为所有内容自动生成python绑定。但是,在头文件中定义了一些枚举,我想让Python端可以使用这些枚举。我的文件如下所示:
foo.h
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
typedef enum otherEnumType {
A, B, C
} otherEnum;
foo.i
%module foo
%{
#include "foo.h"
%}
%module foo
%{
#include "foo.h"
%}
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
在
foo.i
中,我可以在我的C代码中访问CAT
。当然,CAT
、DOG
和HORSE
在Python端是不可用的。如何向Python公开它们?只需在foo.I
文件中包含您想要的foo.h
部分,而不是%include“foo.h”
中处理所有内容:
foo.i
%module foo
%{
#include "foo.h"
%}
%module foo
%{
#include "foo.h"
%}
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
foo.h
typedef enum fooEnumType {
CAT, DOG, HORSE
} fooEnum;
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']
请注意,定义了猫/狗/马,但未定义A/B/C
swig-python foo.i
生成的包装没有错误。我已经尝试过了,但是因为typedef已经在foo.h中定义,所以我得到了一个重新定义错误。即使我没有%在swig端包含“foo.h”
,我仍然必须#在c端包含“foo.h”
。@Fadeecomic添加上述声明不会重新定义fooEnum
。它告诉SWIG为声明生成一个包装器。如果你得到一个重新定义,你实际上在C端定义了两次。我会用证据更新我的答案。如果你仍然得到一个错误,创建一个像我在我的答案中所做的复制问题。