Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c++ - How to create an extension to already wrapped library via SWIG?

I have a library. It is wraped via SWIG. I want to create a plugin to extend it. Plugin requires a class from already wrapped library to run having something like void init( oldT old);. Library is used from Java and c#. Now this plugin also will be used from there. Library and plugin are separate dll's. How to tall SWIG that I already have that oldT type wrapped when creating binding for plugin?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You're looking for %import in the .i file of your plugin. You'll need to either have (or fake) the original .i file from the existing library.

A MCVE targeting Java (but nothing specific to Java) based on a simple header file:

#ifndef EXISTING_H
#define EXISTING_H
struct oldT {
};
#endif

The original library interface file:

%module existing

%{
#include "existing.h"
%}

%include "existing.h"

With that in place we can build the original library:

swig2.0 -Wall -java existing.i 
gcc -Wall -Wextra -shared -o libexisting.so -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux existing_wrap.c 

Which generated libexisting.so and some Java for the oldT type.

Now we write our plugin interface file:

%module plugin

%import "existing.i"
%{
#include "existing.h"
%}

%inline %{
  void plugin_init(struct oldT old) {
    printf("Hello
");
  }
%}

The key thing here is the use of %import to bring in, but not generate wrapper code for the components already wrapped in the library you want to extend.

Again we can compile this:

swig2.0 -Wall -java plugin.i
gcc -Wall -Wextra -shared -o libplugin.so -I/usr/lib/jvm/default-java/include -I/usr/lib/jvm/default-java/include/linux plugin_wrap.c

(Note that for your real scenario you made need to link this against the shared library of the existing library in some scenarios)

Then to test it I wrote a tiny amount of Java:

public class run {
  public static void main(String[] argv) {
    System.loadLibrary("existing");
    System.loadLibrary("plugin");
    plugin.plugin_init(new oldT());
  }
}

Which I compiled and ran with:

javac run.java
LD_LIBRARY_PATH=. java run
Hello

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...