4

I have a function something similar to,

int * print(int count)
{
    int * myarray;
    int i=0;
    myarray = (int *)(malloc(sizeof(int))*count);
    for(i=0;i<count;i++)
    {
      myarray[i] = i;
    }   
   return myarray;
}

Now how can i use myarray in java using JNI

i tried like this

jintArray Java_com_example_testmyapp_MainActivity_JListPrint(JNIEnv* env, jobject thiz)
{
     return print(5);
}

and in java

int a[] = JListPrint()

but my app gets crashed

Pointers, Suggestions please?

Naruto
  • 245
  • 1
  • 6
  • 13

2 Answers2

5

I found this site most useful: http://www3.ntu.edu.sg/home/ehchua/programming/java/JavaNativeInterface.html

#define ARRAY_LENGTH    5

jintArray Java_com_example_testmyapp_MainActivity_JListPrint(JNIEnv *env, jobject thiz)
{
    jintArray intJavaArray = (*env)->NewIntArray(env, ARRAY_LENGTH);
    int *intCArray = print(ARRAY_LENGTH);

    if ( NULL == intJavaArray ) {

        if ( NULL != intCArray ) {
            free(intCArray);
        }
        return NULL;
    }

    (*env)->SetIntArrayRegion(env, intJavaArray, 0, ARRAY_LENGTH, intCArray);

    return intJavaArray;
}
SpacedMonkey
  • 2,725
  • 1
  • 16
  • 17
1

Java primitive arrays are not the same as native arrays. To access them, you must use JNI functions.

For your code, you'll want to use:

  • jintArray NewIntArray()
  • void SetIntArrayRegion(JNIEnv *env, ArrayType array, jsize start, jsize len, NativeType *buf)

See the Oracle documentation on these JNI functions.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151