NDK学习之helloworld

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值