Passing an integer aray fron a c func

S

ss

hi frnds i want to return an integer array fron c prog to java how do i

proceed with it .....i tried with some code but is is not
working......please tell me wat to do and where i m wrong
my code is
class IntArray {
private native int[] sumArray(int[] arr);
public static void main(String[] args) {
IntArray p = new IntArray();
int arr[] = new int[10];
int newarr[]=new int[10];
System.out.println("previous values of newarr");
for(int j=0;j<10;j++)
{arr[j]=j;
System.out.println(arr[j]);
}
newarr=p.sumArray(arr);

//for (int i = 0; i < 10; i++)
// {
//arr = i;
//}
// int sum = p.sumArray(arr,newarr);
System.out.println("new values of newarr");
try{for(int j=0;j<10;j++)
System.out.println(newarr[j]);
}
catch(NullPointerException np){}
System.out.println("value of sum");
// System.out.println("sum = " + sum);
}
static {
System.loadLibrary("IntArray");
}



}


#include<stdio.h>
#include<jni.h>
#include"IntArray.h"
JNIEXPORT jintArray JNICALL Java_IntArray_sumArray
(JNIEnv *env, jobject obj, jintArray arr)
{
jint buf[10];
jint i, sum = 0;
(*env)->GetIntArrayRegion(env, arr, 0, 10, buf);
for (i = 0; i < 10; i++) {
buf= buf+2;
printf("%d",buf);
}
return buf;
}

it is printing the values in c program but it is not retuning the
newarr
 
G

Gordon Beaton

hi frnds i want to return an integer array fron c prog to java how do i
proceed with it .....i tried with some code but is is not
working......please tell me wat to do and where i m wrong
[...]

#include<stdio.h>
#include<jni.h>
#include"IntArray.h"
JNIEXPORT jintArray JNICALL Java_IntArray_sumArray
(JNIEnv *env, jobject obj, jintArray arr)
{
jint buf[10];
jint i, sum = 0;
(*env)->GetIntArrayRegion(env, arr, 0, 10, buf);
for (i = 0; i < 10; i++) {
buf= buf+2;
printf("%d",buf);
}
return buf;
}

it is printing the values in c program but it is not retuning the
newarr


Your code does not return any new array, it returns a pointer to a
buffer local to the C method. There are two serious problems with
this: you pass a pointer to a C int array, not the jintArray expected
by the caller, and it goes out of scope when you return from the
method. Either one of these errors can be expected to crash your JVM.

If you want to return a new array, use NewIntArray() and initialize
the contents of the array with e.g. SetIntArrayRegion().

If you simply want to modify the contents of the existing array, use
SetIntArrayRegion(). Or use GetIntArrayElements(), modify the
resulting C int array, and then ReleaseIntArrayElements() to propagate
your changes back to the original jintArray.

/gordon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,141
Latest member
BlissKeto
Top