Object 的 registerNatives() 方法的作用

来源:互联网 发布:oracle数据库去重复 编辑:程序博客网 时间:2024/05/01 21:12

Normally, in order for the JVM to find your native functions, they have to be named a certain way. e.g., for java.lang.Object.registerNatives, the corresponding C function is named Java_java_lang_Object_registerNatives. By using registerNatives (or rather, the JNI function RegisterNatives), you can name your C functions whatever you want.

Here’s the associated C code (from OpenJDK 6):

static JNINativeMethod methods[] = {
{“hashCode”, “()I”, (void *)&JVM_IHashCode},
{“wait”, “(J)V”, (void *)&JVM_MonitorWait},
{“notify”, “()V”, (void *)&JVM_MonitorNotify},
{“notifyAll”, “()V”, (void *)&JVM_MonitorNotifyAll},
{“clone”, “()Ljava/lang/Object;”, (void *)&JVM_Clone},
};

JNIEXPORT void JNICALL
Java_java_lang_Object_registerNatives(JNIEnv *env, jclass cls)
{
(*env)->RegisterNatives(env, cls,
methods, sizeof(methods)/sizeof(methods[0]));
}
(Notice that Object.getClass is not in the list; it will still be called by the “standard” name of Java_java_lang_Object_getClass.) For the functions listed, the associated C functions are as listed in that table, which is handier than writing a bunch of forwarding functions.

Registering native functions is also useful if you are embedding Java in your C program and want to link to functions within the application itself (as opposed to within a shared library), or the functions being used aren’t otherwise “exported”, since these would not normally be found by the standard method lookup mechanism. Registering native functions can also be used to “rebind” a native method to another C function (useful if your program supports dynamically loading and unloading modules, for example).

I encourage everybody to read the JNI book, which talks about this and much more. :-)

原创粉丝点击