导入C枚举到python而不包括完整的标头? [英] Import C enum into python without including full header?

查看:34
本文介绍了导入C枚举到python而不包括完整的标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以使用SWIG将C头文件中定义的枚举常量公开给Python,而无需使用%include"header.h" 来对整个头进行SWIG?换句话说,我正在手动编写SWIG接口,因为我不想为所有内容自动生成python绑定.但是,在头文件中定义了一些枚举,我希望这些枚举可用于Python端.我的文件如下所示:

Is there an easy way to expose enumerated constants defined in a C header file to Python using SWIG, but without using %include "header.h" to SWIG the entire header? In other words, I'm writing my SWIG interface manually because I do not want to auto-generate python bindings for everything. However, there are enums defined in the header file that I would like to make available to the Python side. My files look like this:

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?

And in foo.i, I can access CAT in my C code. Of course, CAT, DOG, and HORSE are not available on the Python side. How do I expose them to Python?

推荐答案

只需将 foo.h 中想要的部分包括在 foo.i 文件中,而不是%include"foo.h" 处理所有内容:

Just include the portions you want from foo.h in the foo.i file instead of %include "foo.h" that processes everything:

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 生成的包装没有错误.

Note that CAT/DOG/HORSE are defined but A/B/C are not. swig -python foo.i generated the wrapper with no errors.

这篇关于导入C枚举到python而不包括完整的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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