Swig - 包装 C 结构体

2 投票
1 回答
6216 浏览
提问于 2025-04-15 21:50

我正在尝试为使用结构体的C代码编写Python的封装。

modules.c:

struct foo
{
    int a;
};

struct foo bar;

modulues.i

%module nepal
%{
    struct foo
    {
        int a;
    }
%}

extern struct foo bar;

但是在编译时,我遇到了一个错误:

在函数‘Swig_var_bar_set’中:错误:‘bar’未声明(在这个函数中第一次使用)

你能帮我一下,告诉我如何正确地定义导出结构体变量吗?

1 个回答

2

试试这个:

%module nepal
%{
    struct foo
    {
        int a;
    };

    extern struct foo bar;
%}

struct foo
{
    int a;
};

extern struct foo bar;

在 %{ %} 之间的代码会被放到一个包装器里,而下面的代码会被解析来创建这个包装器。把这些内容放在一个头文件里会更简单,这样就不会重复写很多次:

modules.h

struct foo
{
    int a;
};

extern struct foo bar;

modules.c

#include "modules.h"
struct foo bar;

modules.i

%module nepal
%{
    #include "modules.h"
%}

%include "modules.h"

撰写回答