- Joined
- Jun 6, 2012
- Messages
- 1
- Reaction score
- 0
I'm new to JNI programs. I'm doing one JNI code in which I need to pass array value from C to Java. While displaying in java the previous values are considered in array. As i'm new to JNI i couldn't solve this. This is the code:
FieldAccess.java
next.java
FieldAccess.c
The output i'm getting is
Please any one help.
FieldAccess.java
Code:
public class FieldAccess {
public static void main(String args[]) {
next[] Nxt;
next n=new next();
n.h=new String[2];
Nxt=n.arrayFields();
for(int i=0;i<Nxt.length;i++) {
System.out.println("In Java i= "+i+" g Val= "+Nxt[i].g);
for(int j=0;j<2;j++) {
System.out.println("In Java i= "+i+" h Val= "+Nxt[i].h[j]);
}
}
}
static {
System.out.println("Hello");
System.loadLibrary("FieldAccess");
}
}
next.java
Code:
public class next{
public String g;
public String h[];
public native next[] arrayFields();
static {
System.out.println("Hello");
System.loadLibrary("FieldAccess");
}
}
FieldAccess.c
Code:
JNIEXPORT jobjectArray JNICALL Java_next_arrayFields(JNIEnv *env, jobject jobj) {
jobjectArray ret;
int i,j;
printf("Hello");
jclass cls = (*env)->FindClass(env,"next");
ret= (jobjectArray)(*env)->NewObjectArray(env,50,cls,NULL);
if(ret==NULL) {
ret=NULL;
}
for(i=0;i<10;i++) {
jobject remoteNode = (*env)->AllocObject(env,cls);
if (remoteNode == NULL) {
ret = NULL;
}
jfieldID fid,fid1;
fid = (*env)->GetFieldID(env,cls, "g", "Ljava/lang/String;");
fid1 = (*env)->GetFieldID(env,cls, "h", "[Ljava/lang/String;");
if (fid == NULL) {
ret = NULL;
}
if (fid1 == NULL) {
ret = NULL;
}
jstring kk= (*env)->NewStringUTF(env,"Hi");
(*env)->SetObjectField(env,remoteNode, fid,(jstring)kk);
jstring str[2];
for(j=0;j<2;j++) {
str[0]=(*env)->NewStringUTF(env,"jj");
str[1]=(*env)->NewStringUTF(env,"Hello");
}
(*env)->SetObjectField(env,remoteNode, fid1, (jstring)str);
(*env)->SetObjectArrayElement(env,ret, i, remoteNode);
}
return ret;
}
The output i'm getting is
Code:
In Java i= 0 g Val= Hi
In Java i= 0 h Val= Hi
In Java i= 0 h Val= jj
In Java i= 1 g Val= Hi
In Java i= 1 h Val= Hi
In Java i= 1 h Val= jj
In Java i= 2 g Val= Hi
In Java i= 2 h Val= Hi
In Java i= 2 h Val= jj
In Java i= 3 g Val= Hi
In Java i= 3 h Val= Hi
In Java i= 3 h Val= jj
In Java i= 4 g Val= Hi
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out
of range: -253510696
at java.lang.String.getChars(String.java:724)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:394)
at java.lang.StringBuilder.append(StringBuilder.java:120)
at FieldAccess.main(FieldAccess.java:94)
Please any one help.