1 #include <jni.h> 2 #include <stdio.h> 3 4 static jint 5 add(JNIEnv *env, jobject thiz, jint a, jint b) { 6 int result = a + b; 7 printf("%d + %d = %d", a, b, result); 8 return result; 9 } 10 11 static const char *classPathName = "com/example/jniexample/Native"; 12 13 static JNINativeMethod methods[] = { 14 {"add", "(II)I", (void*)add }, 15 }; 16 17 /* 18 * Register several native methods for one class. 19 */ 20 static int registerNativeMethods(JNIEnv* env, const char* className, 21 JNINativeMethod* gMethods, int numMethods) 22 { 23 jclass clazz; 24 25 clazz = env->FindClass(className); 26 if (clazz == NULL) { 27 fprintf(stderr, "Native registration unable to find class '%s'", className); 28 return JNI_FALSE; 29 } 30 if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) { 31 fprintf(stderr, "RegisterNatives failed for '%s'", className); 32 return JNI_FALSE; 33 } 34 35 return JNI_TRUE; 36 } 37 38 /* 39 * Register native methods for all classes we know about. 40 */ 41 static int registerNatives(JNIEnv* env) 42 { 43 if (!registerNativeMethods(env, classPathName, 44 methods, sizeof(methods) / sizeof(methods[0]))) { 45 return JNI_FALSE; 46 } 47 48 return JNI_TRUE; 49 } 50 51 /* 52 * Set some test stuff up. 53 * 54 * Returns the JNI version on success, -1 on failure. 55 */ 56 57 typedef union { 58 JNIEnv* env; 59 void* venv; 60 } UnionJNIEnvToVoid; 61 62 jint JNI_OnLoad(JavaVM* vm, void* reserved) 63 { 64 UnionJNIEnvToVoid uenv; 65 uenv.venv = NULL; 66 jint result = -1; 67 JNIEnv* env = NULL; 68 69 printf("JNI_OnLoad"); 70 71 if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_4) != JNI_OK) { 72 fprintf(stderr, "GetEnv failed"); 73 goto bail; 74 } 75 env = uenv.env; 76 77 if (!registerNatives(env)) { 78 fprintf(stderr, "registerNatives failed"); 79 } 80 81 result = JNI_VERSION_1_4; 82 83 bail: 84 return result; 85 } 86