简体   繁体   English

如何导出在 Eclipse 中嵌入本机库的可运行 JAR?

[英]How to export a runnable JAR embedding a native library in Eclipse?

I have a Java app that makes use of a native library.我有一个使用本机库的 Java 应用程序。 It works fine when I export my runnable JAR, but I have to put the native library in the same folder of the executable.当我导出可运行的 JAR 时它工作正常,但我必须将本机库放在可执行文件的同一文件夹中。

Not sure exists a procedure to do so since it's a native library, but, does exist a way to avoid putting in the same folder the library and embedding that lib inside the runnable JAR?不确定是否存在这样做的过程,因为它是本机库,但是,是否存在避免将库放入同一文件夹并将该库嵌入到可运行 JAR 中的方法?

I use Eclipse and the successfully working procedure I used to enable the native library is the following (it maybe helpful for somebody struggling with this problem):我使用 Eclipse,我用来启用本机库的成功工作过程如下(这可能对解决此问题的人有所帮助):

  1. Select the project in the Package Explorer and right-click;在 Package Explorer 中选择项目并右键单击;
  2. Build Path → Configure Build Path;构建路径→配置构建路径;
  3. Libraries tab;库选项卡;
  4. JRE System library option and Native library location; JRE 系统库选项和本机库位置;
  5. Edit on the right panel;在右侧面板上编辑;
  6. Browse to the library;浏览图书馆;
  7. Close the window.关闭窗口。

To elaborate on the answer I pointed to in the comments, it's possible to deploy a native library inside a JAR.为了详细说明我在评论中指出的答案,可以在 JAR 中部署本机库。 But you have to provide for this in your code.但是你必须在你的代码中提供这一点。 You will have to write your code in a way that it您必须以一种方式编写代码

  • extracts the library from the jar to some temporary location (usually copying what getResourceAsStream() gives you)将库从 jar 中提取到某个临时位置(通常复制getResourceAsStream()给你的内容)
  • and uses the full path name to load the library (using load() instead of loadLibrary )并使用完整路径名加载库(使用load()而不是loadLibrary

Example:例子:

Path tempPath = Paths.get("some/path");
try (InputStream inputStream = myClass.getResourceAsStream("myLibrary")) {
    Files.copy(inputStream, tempPath);
}
System.load(tempPath.toAbsolutePath().toString());

Be aware that some malware scanners prevent loading of libraries from inside the temporary directory so you will have to choose the target path carefully.请注意,某些恶意软件扫描程序会阻止从临时目录中加载库,因此您必须谨慎选择目标路径。

Take a look here: https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo031看看这里: https : //github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo031

The idea is quite simple:这个想法很简单:

  • you have to embed native code inside JAR,你必须在 JAR 中嵌入本机代码,
  • once code is running you have to extract the library,一旦代码运行,你必须提取库,
  • you have to load it inside your code.你必须在你的代码中加载它。

Note that libraries are usually loaded from the file system and it's not possible to load them from the buffer.请注意,库通常是从文件系统加载的,不可能从缓冲区加载它们。 This is why you have to create temporary location.这就是您必须创建临时位置的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM