javac++swigtypemaps

SWIG JAVA typemaps configuration


Here is SWIG typemap, that converts C++ types to Python types.

#ifdef SWIGPYTHON
  %typemap(in) (char *data, size_t datasize) {
    Py_ssize_t len;
    PyBytes_AsStringAndSize($input, &$1, &len);
    $2 = (size_t)len;
  }

  %typemap(in, numinputs=0) (char **data, size_t *datasize)(char *temp, size_t tempsize) {
    $1 = &temp;
    $2 = &tempsize;
  }

  %typemap(argout) (char **data, size_t *datasize) {
    if(*$1) {
      $result = PyBytes_FromStringAndSize(*$1, *$2);
      free(*$1);
    }
  }
#endif

Can you please do the same, but for java language? so the answer will be like

#ifdef SWIGJAVA
  %typemap(in) (char *data, size_t datasize) {
    convertJavaBytesToC++Bytes();
    ...something else...
  }
...

So I need it to generate proper JAVA wrapper code

Function declarations in C++ which I want to translate to JAVA:

public void getFrames(char **data, size_t *datasize) {
    std::string s = getFramesAsString();
    size_t size = s.length();
    char *c = new char[size];
    s.copy(c, size, 0);
    *datasize = size;
    *data = c;
};
public void putFrame(char *data, size_t datasize) {
    const std::lock_guard<std::mutex> lock(frames_mtx);
    frames.push_front(std::string(data, datasize));
};

Solution

  • SWIG already has a typemap for Java which does this for you. To use it all you need to do is use %apply to tell SWIG it is what you want to use for those parameters:

    e.g.

    %module test
    
    %apply (char *STRING, size_t LENGTH) { (char *data, size_t datasize) }
    
    void putFrame(char *data, size_t datasize);
    

    which will generate the following Java function:

      public static void putFrame(byte[] data) {
        ...
    

    Which exactly matches the semantics you want.