#include <jni.h>
#include <string.h>
#include <stdio.h>
#include <android/log.h>
/*
V void void
Z jboolean boolean
I jint int
J jlong long
D jdouble double
F jfloat float
B jbyte byte
C jchar char
S jshort short
数组则以"["开始,用两个字符表示
[I jintArray int[]
[F jfloatArray float[]
[B jbyteArray byte[]
[C jcharArray char[]
[S jshortArray short[]
[D jdoubleArray double[]
[J jlongArray long[]
[Z jbooleanArray boolean[]
*/
jstring showHello(JNIEnv* env, jobject thiz)
{
__android_log_print(ANDROID_LOG_DEBUG,"helloJni","jni testing..................................\n");
// 获取CaldroidSampleActivity对应的jobject对象,为什么这里的thiz不是CaldroidSampleActivity对象呢???
jclass clazz_caldroid_ac = (*env)->FindClass(env, "com/caldroidsample/CaldroidSampleActivity");
jmethodID methodID = (*env)->GetMethodID(env,clazz_caldroid_ac,"<init>","()V");
jobject obj =(*env)->NewObject(env,clazz_caldroid_ac,methodID);
// 获取CaldroidSampleActivity类中属性helloStr的值,并打印
jfieldID hello_fieldID = (*env)->GetFieldID(env,clazz_caldroid_ac,"helloStr","Ljava/lang/String;");
jstring hello_str = (jstring)(*env)->GetObjectField(env,obj,hello_fieldID);
const char* hello_str_char = (*env)->GetStringUTFChars(env,hello_str, 0);
__android_log_print(ANDROID_LOG_DEBUG,"helloJni","hello_str = %s\n",hello_str_char);
// 记得要及时释放,避免内存泄露
(*env)->ReleaseStringUTFChars(env,hello_str,hello_str_char);
// 给CaldroidSampleActivity类中属性helloStr重新赋值
char *buf = (char*)malloc(15);
strcpy(buf, "jni,1234567890");
jstring jstrBuf = (*env)->NewStringUTF(env, buf);
(*env)->SetObjectField(env,obj,hello_fieldID,jstrBuf);
// 获取新值,打印
jstring hello_str_new = (*env)->GetObjectField(env,obj,hello_fieldID);
const char* hello_str_char_new = (*env)->GetStringUTFChars(env,hello_str_new, 0);
__android_log_print(ANDROID_LOG_DEBUG,"helloJni","hello_str_new = %s\n",hello_str_char_new);
(*env)->ReleaseStringUTFChars(env,hello_str_new,hello_str_char_new);
return (*env)->NewStringUTF(env, "Hello,JNI,nice to meet you!!!");
}
jint JNI_OnLoad(JavaVM* pVm, void* reserved) {
JNIEnv* env;
if ((*pVm)->GetEnv(pVm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
JNINativeMethod nm[2];
nm[0].name = "showHello";
nm[0].signature = "()Ljava/lang/String;";
nm[0].fnPtr = (void*)showHello;
jclass cls = (*env)->FindClass(env, "com/caldroidsample/CaldroidSampleActivity");
//Register methods with env->RegisterNatives.
(*env)->RegisterNatives(env, cls, nm, 1);
return JNI_VERSION_1_6;
}
NDK学习之helloworld
最新推荐文章于 2024-11-14 21:05:44 发布