Returning an array from C to Java using SWIG

I have a C function, for example:

void get_data(const obj_t *obj, short const **data, int *data_len);

I wrote this so specifically for Swig, as

const short *get_data(const obj_t *obj, int *data_len);

causes problems because SWIG type templates are not smart enough to associate data_len with the return value.

In Java, I want to be able to call this function as follows:

short data[]= mylib.get_data(obj);

But I cannot figure out how to get the output parameter of the array as a return value. With Ruby and Python, this works great because SWIG for these languages ​​supports return output parameters as return values ​​(since languages ​​can have multiple return values).

How can I make this work with Java?

+5
source share
1 answer

, :

typedef struct { } obj_t;

const short *get_data(const obj_t *obj, int *data_len) {
  (void)obj;
  static short arr[] = {1,2,3,4,5};
  *data_len = sizeof(arr)/sizeof(*arr);
  return arr;
}

, , :

%module test

%{
#include "test.h"
%}

data_len. Java, , , , , , Java .

%typemap(in,numinputs=0,noblock=1) int *data_len {
   int temp_len;
   $1 = &temp_len;
}

, SWIG short[] Java :

%typemap(jstype) const short *get_data "short[]"
%typemap(jtype) const short *get_data "short[]"

jshortArray JNI - -, :

%typemap(jni) const short *get_data "jshortArray"
%typemap(javaout) const short *get_data {
  return $jnicall;
}

, , , , Java . free() , , .

%typemap(out) const short *get_data {
  $result = JCALL1(NewShortArray, jenv, temp_len);
  JCALL4(SetShortArrayRegion, jenv, $result, 0, temp_len, $1);
  // If the result was malloc()'d free it here
}

, SWIG , :

%include "test.h"

:

public class run {
  public static void main(String argv[]) {
    System.loadLibrary("test");
    obj_t obj = new obj_t();
    short[] result = test.get_data(obj);
    for (int i = 0; i < result.length; ++i) {
      System.out.println(result[i]);
    }
  }
}

:

1
2
3
4
5

:

void get_data(const obj_t *obj, short const **data, int *data_len);

, , Java. Java, , . GetShortArrayElements/ReleaseShortArrayElements 0 .

, Java , :

public class ret {
  public static void foo(int arr[]) {
    arr[0] = -100;
  }

  public static void main(String argv[]) {
    int arr[] = new int[10];
    System.out.println(arr[0]);
    foo(arr);
    System.out.println(arr[0]);
  }
}
+7

All Articles