如何在 JAR 中捆绑本机库和 JNI 库? [英] How to bundle a native library and a JNI library inside a JAR?

查看:32
本文介绍了如何在 JAR 中捆绑本机库和 JNI 库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有问题的图书馆是东京内阁.

我想要在一个 JAR 文件中包含本机库、JNI 库和所有 Java API 类,以避免重新分发带来的麻烦.

I want is to have the native library, JNI library, and all Java API classes in one JAR file to avoid redistribution headaches.

似乎有在 GitHub 上的尝试,但是

  1. 它不包括实际的本机库,仅包括 JNI 库.
  2. 它似乎特定于 Leiningen 的本机依赖项插件(它不能作为可重新分发).
  1. It does not include the actual native library, only JNI library.
  2. It seems to be specific to Leiningen's native dependencies plugin (it won't work as a redistributable).

问题是,我可以将所有内容捆绑在一个 JAR 中并重新分发吗?如果是,如何?

The question is, can I bundle everything in one JAR and redistribute it? If yes, how?

P.S.:是的,我意识到它可能会影响可移植性.

P.S.: Yes, I realize it may have portability implications.

推荐答案

可以创建包含所有依赖项的单个 JAR 文件,包括一个或多个平台的本机 JNI 库.基本机制是使用 System.load(File) 加载库,而不是典型的 System.loadLibrary(String) 搜索 java.library.path 系统属性.这种方法使安装更简单,因为用户不必在他的系统上安装 JNI 库,但代价是可能不支持所有平台,因为单个 JAR 文件中可能不包含某个平台的特定库.

It is possible to create a single JAR file with all dependencies including the native JNI libraries for one or more platforms. The basic mechanism is to use System.load(File) to load the library instead of the typical System.loadLibrary(String) which searches the java.library.path system property. This method makes installation much simpler as the user does not have to install the JNI library on his system, at the expense, however, that all platforms might not be supported as the specific library for a platform might not be included in the single JAR file.

流程如下:

  • 在特定于平台的位置的 JAR 文件中包含本机 JNI 库,例如在 NATIVE/${os.arch}/${os.name}/libname.lib
  • 在主类的静态初始化器中创建代码以
    • 计算当前的 os.arch 和 os.name
    • 使用 Class.getResource(String) 在 JAR 文件中的预定义位置查找库
    • 如果存在,将其解压缩到一个临时文件中并使用 System.load(File) 加载它.

    我添加了为 jzmq(ZeroMQ(无耻插件)的 Java 绑定)执行此操作的功能.代码可以在这里找到.jzmq 代码使用混合解决方案,因此如果无法加载嵌入式库,代码将返回沿 java.library.path 搜索 JNI 库.

    I added functionality to do this for jzmq, the Java bindings of ZeroMQ (shameless plug). The code can be found here. The jzmq code uses a hybrid solution so that if an embedded library cannot be loaded, the code will revert to searching for the JNI library along the java.library.path.

    这篇关于如何在 JAR 中捆绑本机库和 JNI 库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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