How to create an extension to already wrapped library via SWIG?

孤人 提交于 2019-11-29 17:22:05
Flexo

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\n");
  }
%}

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!