registerNatives() 方法有什么作用? [英] What does the registerNatives() method do?

查看:24
本文介绍了registerNatives() 方法有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java中Object类的私有静态方法registerNatives()是做什么的?

In java, what does the private static method registerNatives() of the Object class do?

推荐答案

其他答案在技术上是正确的,但对于没有 JNI 经验的人来说不是很有用.:-)

The other answers are technically correct, but not very useful for someone with no JNI experience. :-)

通常,为了让 JVM 找到您的本机函数,它们必须以某种方式命名.例如,对于java.lang.Object.registerNatives,对应的C 函数名为Java_java_lang_Object_registerNatives.通过使用 registerNatives(或者更确切地说,JNI 函数 RegisterNatives),您可以随意命名 C 函数.

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.

这是相关的 C 代码(来自 OpenJDK 6):

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]));
}

(注意 Object.getClass 不在列表中;它仍然会被 Java_java_lang_Object_getClass 的标准"名称调用.)对于列出的函数,相关的C函数如该表所列,比写一堆转发函数要方便.

(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.

如果您在 C 程序中嵌入 Java 并希望链接到应用程序本身中的函数(而不是共享库中),或者正在使用的函数没有以其他方式导出",则注册本机函数也很有用,因为这些通常不会被标准方法查找机制找到.注册本机函数还可用于将本机方法重新绑定"到另一个 C 函数(例如,如果您的程序支持动态加载和卸载模块,则很有用).

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).

我鼓励大家阅读 JNI 书籍,它谈到了这个以及更多.:-)

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

这篇关于registerNatives() 方法有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆