1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
#include <jni.h>
#include <myrica.h>
#include <iostream>
// save global jvm pointer for futher usage
JavaVM *jvm_global_ = nullptr;
// main jni clazz
static const char *jni_clazz_impl_ = "cn/az/code/jni/HelloJni";
// native methods
static JNINativeMethod jni_methods_[] = {
{(char *)"native_say", (char *)"()V", (void *)jni_native_say}};
/**
* @brief Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv *env, const char *className, JNINativeMethod *gMethods, int numMethods)
{
jclass clazz = env->FindClass(className);
if (clazz == NULL)
{
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0)
{
return JNI_FALSE;
}
return JNI_TRUE;
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void* reserved) {
std::cout << "jvm OnLoad" << std::endl;
jvm_global_ = jvm;
// Real Jni Operation Instance
JNIEnv *jni_env = nullptr;
// Get current JniEnv pointer
jint r = jvm_global_->GetEnv(reinterpret_cast<void **>(&jni_env), JNI_VERSION_1_8);
// if fail, return
if (r == JNI_FALSE) {
std::cerr << "fail to get env" << std::endl;
return JNI_FALSE;
}
// register native methods
jint ret = registerNativeMethods(jni_env, jni_clazz_impl_, jni_methods_, sizeof(jni_methods_) / sizeof(jni_methods_[0]));
if (JNI_TRUE == ret)
std::cout << "native methods registered" << std::endl;
// must return valid JNI Version
return JNI_VERSION_1_8;
}
|