Search code examples
javacarraysjava-native-interfaceswig

Swig: pass byte array in Java to C


I am trying to create Java implementation for passing byte [] to C using Swig.

Swig:

%include "typemaps.i"
%apply(char *STRING, int LENGTH) { (char *buff, int len) }; 
%inline {
   typedef struct {
        char*         buff;        
        int           len;  
  } workit_t;
}

In my generated java class (workit_t.java), the parameter buff is a String, instead of a byte [].

Java:

public void setBuff(String value){
 ... 
}

What am I doing wrong in my swig definition?

When I write a simple swig definition with no struct, I get the desired type of parameter.

Swig:

%include "typemaps.i"
%apply(char *STRING, int LENGTH) { (char *buff1, int *len1) };

Java:

public static void Mathit(byte[] buff1, byte[] buff2) {
...
}

Solution

  • Well, I have been able to get it right.

    Before:

    %include "typemaps.i"
    %apply(char *STRING, int LENGTH) { (char *buff, int len) }; 
    %inline {
       typedef struct {
            char*         buff;        
            int           len;  
      } workit_t;
    }
    

    Now:

    %include various.i                    
    %apply char *BYTE { char *buff };  //map a Java byte[] array to a C char array
    %inline {
       typedef struct {
            char*         buff;        
            int           len;  
       } workit_t;
    }
    

    Or:

    %include various.i                    
    %apply char *NIOBUFFER { char *buff }; //map Java nio buffers to C char array
    %inline {
       typedef struct {
            char*         buff;        
            int           len;  
       } workit_t;
    }