1 /*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "simplejni native.cpp"
18 #include <utils/Log.h>
19
20 #include <stdio.h>
21
22 #include "jni.h"
23
24 static jint
add(JNIEnv * env,jobject thiz,jint a,jint b)25 add(JNIEnv *env, jobject thiz, jint a, jint b) {
26 int result = a + b;
27 ALOGI("%d + %d = %d", a, b, result);
28 return result;
29 }
30
31 static const char *classPathName = "com/example/android/simplejni/Native";
32
33 static JNINativeMethod methods[] = {
34 {"add", "(II)I", (void*)add },
35 };
36
37 /*
38 * Register several native methods for one class.
39 */
registerNativeMethods(JNIEnv * env,const char * className,JNINativeMethod * gMethods,int numMethods)40 static int registerNativeMethods(JNIEnv* env, const char* className,
41 JNINativeMethod* gMethods, int numMethods)
42 {
43 jclass clazz;
44
45 clazz = env->FindClass(className);
46 if (clazz == NULL) {
47 ALOGE("Native registration unable to find class '%s'", className);
48 return JNI_FALSE;
49 }
50 if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
51 ALOGE("RegisterNatives failed for '%s'", className);
52 return JNI_FALSE;
53 }
54
55 return JNI_TRUE;
56 }
57
58 /*
59 * Register native methods for all classes we know about.
60 *
61 * returns JNI_TRUE on success.
62 */
registerNatives(JNIEnv * env)63 static int registerNatives(JNIEnv* env)
64 {
65 if (!registerNativeMethods(env, classPathName,
66 methods, sizeof(methods) / sizeof(methods[0]))) {
67 return JNI_FALSE;
68 }
69
70 return JNI_TRUE;
71 }
72
73
74 // ----------------------------------------------------------------------------
75
76 /*
77 * This is called by the VM when the shared library is first loaded.
78 */
79
80 typedef union {
81 JNIEnv* env;
82 void* venv;
83 } UnionJNIEnvToVoid;
84
JNI_OnLoad(JavaVM * vm,void * reserved)85 jint JNI_OnLoad(JavaVM* vm, void* reserved)
86 {
87 UnionJNIEnvToVoid uenv;
88 uenv.venv = NULL;
89 jint result = -1;
90 JNIEnv* env = NULL;
91
92 ALOGI("JNI_OnLoad");
93
94 if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) {
95 ALOGE("ERROR: GetEnv failed");
96 goto bail;
97 }
98 env = uenv.env;
99
100 if (registerNatives(env) != JNI_TRUE) {
101 ALOGE("ERROR: registerNatives failed");
102 goto bail;
103 }
104
105 result = JNI_VERSION_1_4;
106
107 bail:
108 return result;
109 }
110