Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
880 views
in Technique[技术] by (71.8m points)

c++ - extending 'incomplete' types (SWIG)

I'm looking for a way to extend (i.e. add new members to a type using the %extend directive) a type that is defined in the library file itself while the header files of the library provide only a forward declaration for the type.

Treating the type as if its definition is known at compile time, leads to the following warning:

Warning 303: %extend defined for an undeclared class [name of the type].

Is anyone aware of a solution or a workaround for this problem? I'm sure there is one, since SWIG's documentation states that swig assumes that the unknown type is a struct or a union each time it finds one.

Many thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can very easily add extra methods to a type which has been forward declared in SWIG by giving it an empty definition in the interface, e.g.

test.h:

// Forward declare foo
struct foo;

test.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
  }
}

The key is that in the interface file you're not actually writing C or C++ in the normal sense, you're telling SWIG what types and what parts of each type to wrap.

Since you will presumably be relying on the library to create and destroy instances you'll also want to add:

%nodefaultctor foo; 
%nodefaultdtor foo; 

In the interface file to suppress the constructor/destructor generation and force it to go through the library.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...