加载JNI库时,如何使用实际的库名称进行映射 [英] While loading JNI library, how the mapping happens with the actual library name

查看:180
本文介绍了加载JNI库时,如何使用实际的库名称进行映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用

System.loadLibrary("hello")

现在我知道该库名称是指用于Windows的hello.dll libhello.so用于基于Unix 的系统.

Now I came to know that this library name refers to hello.dll for windows and libhello.so for unix based system.

那么这些与平台相关的更改发生在哪里?

So where these platform dependent changes happens?

JRE正在这样做吗?

Is JRE doing this?

推荐答案

tl; dr

依赖于平台的库名称是在Java虚拟机的本机方法中构建的. 实际的算法只是在平台名称前添加前缀/后缀/后缀:

The platform dependent library name is built in native methods of the Java Virtual Machine. The actual algorithm simply prepends/appends a platform specific prefix/suffix to the name:

  • Windows:"hello"-> "hello.dll"
  • Linux/Solaris:"hello" "libhello.so"
  • Mac:"hello"-> "libhello.dylib"
  • Windows: "hello" -> "hello.dll"
  • Linux/Solaris: "hello" "libhello.so"
  • Mac: "hello" -> "libhello.dylib"

长版:

有两种JDK Java方法可以处理加载库和/或库名:

There are a couple of JDK Java methods which deal with loading libraries and/or library names:

java.lang.System.loadLibrary(String name)
java.lang.System.mapLibraryName(String name)
java.lang.Runtime.loadLibrary(String name) 
java.lang.ClassLoader.loadLibrary(String name)

著名的System.loadLibrary实际上调用了Runtime.loadLibrary,后者又调用了ClassLoader.loadLibrary. 最后,这些方法的实现调用以下本机方法,这些本机方法转换给定的库名 进入平台的特定名称:

The famous System.loadLibrary actually calls Runtime.loadLibrary which calls ClassLoader.loadLibrary. In the end the implementations of these methods call the following native methods which translate the given library name into the platform specific name:

native java.lang.System.mapLibraryName(String name)
native java.lang.ClassLoader$NativeLibrary.findBuiltinLib(String name) 

这些本机方法的实现可以在(链接到OpenJDK版本)中找到:

The implementations of these native methods can be found in (link to the OpenJDK versions):

  • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/native/java/lang/System.c#l466
  • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/native/java/lang/ClassLoader.c#l495

这两种方法都采用相同的算法来构建实际的库名, 在前缀JNI_LIB_PREFIX之前添加后缀JNI_LIB_SUFFIX.

Both methods implement the same algorithm to build the actual library name, prepending the prefix JNI_LIB_PREFIX and appending the suffix JNI_LIB_SUFFIX.

最后,在依赖于平台的包含文件中定义了宏JNI_LIB_PREFIXJNI_LIB_SUFFIX,即

In the end the macros JNI_LIB_PREFIX and JNI_LIB_SUFFIX are defined in platform dependent include files, namely

  • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/windows/javavm/export/jvm_md.h#l42
  • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/solaris/javavm/export/jvm_md.h#l43
  • http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/macosx/javavm/export/jvm_md.h#l43

这篇关于加载JNI库时,如何使用实际的库名称进行映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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