How To Use The Jni To Change The Fields Of A Java Class
I am using a c native function to change the integer fields of a java class. Basically i want to see how the call by reference can be implemented using JNI. But i am getting the er
Solution 1:
The name and signature of your C method is wrong, the name must be Java_PackageName_ClassName_CfunctionName
If you call it from a class named MyClass
and its package name is com.kpit.myfirstndkapp
then your method must be declared as
JNIEXPORT void JNICALL Java_com_kpit_myfirstndkapp_MyClass_callToChangeJNI(...)
Solution 2:
Finally, after some debugging i got the exact code which changes the values of a and b to new values. Here is the correct code:
Java code:
package com.kpit.myfirstndkapp;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
classmyclass {
inta=1;
intb=2;
publicnativevoidcallTochangeJNI();
static {
System.loadLibrary("sum_jni");
}
}
publicclasssumextendsActivity {
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sum);
myclassmyobject=newmyclass();
System.out.println("calling the jni native method");
myobject.callTochangeJNI();
System.out.println("returned from jni native method one");
System.out.format(" a = %d%n....", myobject.a);
System.out.format("b = %d%n...", myobject.b);
} }
C native library code:
#include <stdio.h>#include <stdlib.h>#include <jni.h>
void Java_com_kpit_myfirstndkapp_myclass_callTochangeJNI(JNIEnv* env,
jobject obj)
{
jfieldID fid;
jmethodID mid;
jclass myclass;
printf(" Inside the JNI native method \n");
jclass cls = (*env)->GetObjectClass(env, obj);
fid = (*env)->GetFieldID(env,cls,"a","I");
(*env)->SetIntField(env, obj ,fid,3);
fid = (*env)->GetFieldID(env,cls,"b","I");
(*env)->SetIntField(env, obj ,fid,4);
}
This works and i get the below log on the screen:
07-26 06:42:30.838: I/System.out(551): calling the jni native method
07-26 06:42:30.859: I/System.out(551): returned from jni native method one
07-26 06:42:30.859: I/System.out(551): a = 3
07-26 06:42:30.868: I/System.out(551): ....b = 4
07-26 06:42:31.179: I/Process(93): Sending signal. PID: 551 SIG: 3
07-26 06:42:31.179: I/dalvikvm(551): threadid=3: reacting to signal 3
07-26 06:42:31.269: I/dalvikvm(551): Wrote stack traces to '/data/anr/traces.txt'
07-26 06:42:31.348: D/gralloc_goldfish(551): Emulator without GPU emulation detected.
07-26 06:42:31.498: I/ActivityManager(93): Displayed com.kpit.myfirstndkapp/.sum:
+2s524ms (total +1m25s486ms) 07-26 06:42:31.558: I/ActivityManager(93): Displayed com.android.launcher/com.android.launcher2.Launcher: +1m25s544ms
I am very thankful to stackoverflow.com to provide such a helping platform for learners like me
Post a Comment for "How To Use The Jni To Change The Fields Of A Java Class"