JNI Template

#include <jni.h>
#include <string>
#include <assert.h>

JavaVM *globleVM = NULL;
//extern "C"
//jstring
//Java_com_feicheninfo_testjni_MainActivity_stringFromJNI(
// JNIEnv *env,
// jobject /* this */) {
// std::string hello = "Hello from C++";
// return env->NewStringUTF(hello.c_str());
//}

//JNI
__attribute__((section (".mytext")))jstring check8(JNIEnv *env, jobject thiz, jstring name) {

const char *str;
str = env->GetStringUTFChars(name, NULL);

if (strcmp(str, "feichen") == 0) {
return name;
}
else {
return env->NewStringUTF("cann't find this account");
}
}

//自定义的JNI_OnLoad,用于混淆native函数名
#define JNIREG_CLASS "com/feicheninfo/testjni/MainActivity"//指定要注册的类

/**
* Table of methods associated with a single class.
*/

static JNINativeMethod gMethods[] = {//绑定,注意,V,Z签名的返回值不能有分号“;”
{"check7", "(Ljava/lang/String;)Ljava/lang/String;", (void *) check8},
};

/*
* Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv *env, const char *className,
JNINativeMethod *gMethods, int numMethods) {
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
return JNI_FALSE;
}

return JNI_TRUE;
}

static int registerNatives(JNIEnv *env) {
if (!registerNativeMethods(env, JNIREG_CLASS, gMethods, sizeof(gMethods) / sizeof(gMethods[0])))
return JNI_FALSE;

return JNI_TRUE;
}

jint JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = NULL;
jint result = -1;

if (vm->GetEnv((void **) &env, JNI_VERSION_1_4) != JNI_OK) {
return -1;
}
assert(env == NULL);

if (!registerNatives(env)) {//注册
return -1;
}
/* success -- return valid version number */
globleVM = vm;
result = JNI_VERSION_1_4;

return result;
}

void JNI_OnUnload(JavaVM *vm, void *reserved) {

globleVM = NULL;
}
posted @ 2016-10-08 04:19  飞晨信息  阅读(124)  评论(0)    收藏  举报