扩展“不完整”类型(SWIG)

c0f*_*lex 2 c c++ swig language-binding interface

我正在寻找一种方法来扩展(即使用 %extend 指令向类型添加新成员)在库文件本身中定义的类型,而库的头文件仅提供该类型的前向声明。

将类型视为其定义在编译时已知,会导致以下警告:

Warning 303: %extend defined for an undeclared class [name of the type].
Run Code Online (Sandbox Code Playgroud)

有没有人知道这个问题的解决方案或解决方法?我确定有一个,因为 SWIG 的文档指出 swig 每次找到一个时都假定未知类型是结构体或联合体。

提前谢谢了!

Fle*_*exo 5

通过在接口中给它一个空定义,您可以非常轻松地向已在 SWIG 中向前声明的类型添加额外的方法,例如

测试.h:

// Forward declare foo
struct foo;
Run Code Online (Sandbox Code Playgroud)

测试.i:

%module test

// Tell SWIG to wrap foo "properly", but that you don't know anything about it:
struct foo { };

%include "test.h"

%extend foo {
  void bar() {
    // Do stuff, probably with $self, here
  }
}
Run Code Online (Sandbox Code Playgroud)

关键是,在接口文件中,您实际上并不是在编写正常意义上的 C 或 C++,而是告诉 SWIG 哪些类型以及每种类型的哪些部分要包装。

由于您可能会依赖库来创建和销毁实例,因此您还需要添加:

%nodefaultctor foo; 
%nodefaultdtor foo; 
Run Code Online (Sandbox Code Playgroud)

在接口文件中抑制构造函数/析构函数的生成并强制它通过库。