您的位置:首页 > 其它

NDK开发笔记(三)---JNI的学习

2011-03-16 17:08 134 查看
一.本文是主要写GetFieldID,GetMethodID方法的使用

jclass clazz=(*env)->GetObjectClass(env,thiz);//其中的clazz就是Natvie class.

public class Native {
public  String value="hello";
/**
* this will return from JNI
* @return
*/
public static int number=0;
public static native String stringFromJNI();
/**
* pass the message to the JNI and
* @param meg
* @return JNI deal it message
*/
public static native String getMessage(String meg);
public  native void getValue();

public void showMessage(){
System.out.println("call the show Message");
}
}


开始我在写这个程序的时候一直报GetFileId ..No such "value".

找了好久才发现 我在Native.java中定义的 和getValue()也是用static

然后定义的value不是static.

在fid=(*env)->GetFieldID(env,clazz,"value","Ljava/lang/String;"); 报错,是因为static方法中必须要用static的变量

所以我把getValue()方法的static方法去掉,下面是ok的代码。

void Java_com_android_jni_Native_getValue(JNIEnv * env,jobject thiz){
jfieldID fid;
jfieldID fNumberId;
jstring jstr;
jmethodID mid;
const char * szTemp;
jclass clazz=(*env)->GetObjectClass(env,thiz);
print(clazz);
fid=(*env)->GetFieldID(env,clazz,"value","Ljava/lang/String;");
if(fid==NULL){
return;
}
jstr=(*env)->GetObjectField(env,thiz,fid);
szTemp=(*env)->GetStringUTFChars(env,jstr,NULL);
print(szTemp);
(*env)->ReleaseStringUTFChars(env,jstr,szTemp);
jstr=(*env)->NewStringUTF(env,"hello world");
if(jstr==NULL)
return;
(*env)->SetObjectField(env,thiz,fid,jstr);
//call the method showMessage
fNumberId=(*env)->GetStaticFieldID(env,clazz,"number","I");
if(fNumberId==NULL)
return;
jint num=(*env)->GetStaticIntField(env,clazz,fNumberId);
//print(num);
(*env)->SetStaticIntField(env,clazz,fNumberId,2);
mid=(*env)->GetMethodID(env,clazz,"showMessage","()V");
if(mid==NULL)
return ;
(*env)->CallVoidMethod(env,thiz,mid);
}


我本来想全部用static来解决就是

fid=(*env)->GetStaticFieldID(env,clazz,"value","Ljava/lang/String;");

不知道什么原因,还是出现上面的错误。。后续来改。

今天试getMethodId();

mid=(*env)->GetMethodID(env,clazz,"showMessage","()V");//showMessage为Java中的方法,"()V"为该方法是return void的方法。

(*env)->CallVoidMethod(env,thiz,mid);

与GetMethodID相对应的是Call**Method().

对应static的属性一定要用static的属性。

fNumberId=(*env)->GetStaticFieldID(env,clazz,"number","I");

if(fNumberId==NULL)

return;

jint num=(*env)->GetStaticIntField(env,clazz,fNumberId);

//print(num);

(*env)->SetStaticIntField(env,clazz,fNumberId,2);

需要源码的请留言给出mail的地址。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: