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?

0

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.