How to pass an array (long array in java) from Java to C ++ using Swig

I have an example .h file as shown below:

class Test
{
public:
       void SelectValues(long long values[])
};

I used SWIG and created a JNI interface below the .i file

%module MyLib
%include "carrays.i"
%array_functions(long long, long_long_array )


%{
  #include "Test.h"
%}

/* Let just grab the original header file here */
%include <windows.i> /*This line is used for calling conventions*/ 
% include "Test.h"

When I create a Java method, it creates as:

public void SelectValues(SWIGTYPE_p_long_long includeKeys)

Also for a JNI file, it takes an argument like jlongArray, but only for simple jlong. Due to this problem, I cannot create an array as long as long[]={1L,2L}, and pass it above to the Java method to call the corresponding JNI method.

I want SWIG to create an interface in such a way that I can pass the above array to my C ++ method.

I read this question , but it did not help me see how to pass an array from Java to C ++.

+5
source share
1 answer

, array_functions, , , ++, Java. - :

SWIGTYPE_p_long_long array = MyLib.new_long_long_array(100); // new array with 100 elements.
for (int i = 0; i < 100; ++i) {
  long_long_array_setitem(array, i, i);
}
new Test().SelectValues(array);

array - "" ++- , / Java .

, , "" Java. SWIG array_class, , , . , array_class(long long, LongLongArray) array_functions, :

LongLongArray array = new LongLongArray(100);
for (int i = 0; i < 100; ++i) {
   array.setitem(i,i); 
}
new Test().SelectValues(array.cast());

SWIG , , . SelectValues, , , .

( %inline d )

%module MyLib

%{
#include <iostream>
%}

%typemap(jtype) long long values[] "long[]"
%typemap(jstype) long long values[] "long[]"
%typemap(javain) long long values[] "$javainput"
%typemap(jni) long long values[] "jlongArray"
%typemap(in) long long values[] {
  jboolean isCopy;
  $1 = JCALL2(GetLongArrayElements, jenv, $input, &isCopy);
}

%inline %{
class Test
{
public:
  void SelectValues(long long values[]) {
    while (*values) {
      std::cout << *values++ << "\n";
    }
  }
};
%}

, SWIG- proxy, JNI long[], Java. Java- Java JNI, javain - . ++ JNI jlongArray, .

in, jlongArray long long[] ++ - JNI, , JVM, . ( , Java, )

:

public class run {
  public static void main(String[] argv) {
    System.loadLibrary("mylib");
    long arr[] = {100,99,1,0}; // Terminate with 0!
    new Test().SelectValues(arr);
  }
}

, .

+2

All Articles