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

前端 未结 1 2004
青春惊慌失措
青春惊慌失措 2020-12-22 07:41

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

相关标签:
1条回答
  • 2020-12-22 08:28

    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
    
    0 讨论(0)
提交回复
热议问题