【问题标题】:Import C enum into python without including full header?将C枚举导入python而不包括完整标题?
【发布时间】:2018-02-16 21:45:43
【问题描述】:

是否有一种简单的方法可以使用 SWIG 将 C 头文件中定义的枚举常量公开给 Python,但不使用 %include "header.h" 来 SWIG 整个头文件?换句话说,我正在手动编写我的 SWIG 界面,因为我不想为所有内容自动生成 python 绑定。但是,我想让 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?

【问题讨论】:

    标签: python c enums swig


    【解决方案1】:

    只需在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 生成的包装器没有错误。

    【讨论】:

    • 我试过了,但是因为 typedef 已经在 foo.h 中定义了,我得到了一个重新定义错误。即使我在 swig 方面不%include "foo.h",我仍然必须在 c 方面#include "foo.h"。
    • @Fadecomic 添加如上所示的声明不会重新定义fooEnum。它告诉 SWIG 为声明生成一个包装器。如果要重新定义,实际上是在 C 端定义了两次。我会用证明更新我的答案。如果您仍然遇到错误,请创建一个 minimal reproducible example,就像我在重现问题的答案中所做的那样。
    猜你喜欢
    • 2021-01-13
    • 2010-09-06
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多