使用 JNI 链接静态库 [英] Linking static library with JNI

查看:68
本文介绍了使用 JNI 链接静态库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 8 之前的 Java 版本要求本机代码位于共享库中,但我读到 Java 8 可以将静态链接库与 JNI 一起使用.我已经搜索了示例,但找不到任何示例.

Java versions prior Java 8 requires native code to be in a shared library, but I've read that with Java 8 it's possible to use static linked libraries with JNI. I have searched for examples but couldn't find any.

如何将 JNI 库静态链接到我的 Java 应用程序中?

How can I statically link a JNI library into my java application?

推荐答案

Java SE 8 规范已更改为支持静态链接,并且在 JDK 中实现了静态链接.这在 System.loadLibrary.它所指的 JNI 规范的部分是 此处此处.

The Java SE 8 specification has been changed to support static linking, and static linking is implemented in the JDK. This is mentioned briefly in the spec for System.loadLibrary. The sections of the JNI Specification to which it refers are here and here.

本地方法签名和数据类型对于静态和动态链接的方法是相同的.不过,您可能需要修改 JDK 生成文件才能使其静态链接您的库.

Native method signatures and data types are the same for statically and dynamically linked methods. You might have to hack on the JDK makefiles to get it to link your library statically, though.

一个显着的区别是静态库的初始化方式.动态库通过调用JNI_OnLoad 函数初始化,通过调用JNI_OnUnload 取消初始化.每个动态库都可以有自己的这些函数版本.如果有多个静态链接的库,显然它们不能都具有相同名称的函数.对于名为 libname 的静态库,加载/卸载函数是 JNI_OnLoad_libnameJNI_OnUnload_libname.

One significant difference is the way static libraries are initialized. Dynamic libraries are initialized by calling the JNI_OnLoad function and are deinitialized by calling JNI_OnUnload. Each dynamic library can have its own version of these functions. If there are multiple statically linked libraries, clearly they can't all have functions with these same names. For a static library named libname the load/unload functions are JNI_OnLoad_libname and JNI_OnUnload_libname.

JNI_OnLoad_libname 函数必须返回 JNI_VERSION_1_8 或更高的值.如果没有,JVM 将忽略静态库.

The JNI_OnLoad_libname function must return a value of JNI_VERSION_1_8 or higher. If it doesn't, the JVM will ignore the static library.

基本上,如果你调用System.loadLibrary("foo"),系统会在运行的可执行映像中寻找函数JNI_OnLoad_foo,如果找到,它假设库是静态链接的,并且在运行映像中搜索其本机方法.如果未找到 JNI_OnLoad_foo,则进行通常的动态库搜索和加载,并从如此找到的动态库链接本机方法.

Basically, if you call System.loadLibrary("foo"), the system looks for the function JNI_OnLoad_foo in the running executable image, and if it's found, it assumes that the library is statically linked, and its native methods are searched for within the running image. If JNI_OnLoad_foo is not found, then the usual searching and loading of dynamic libraries takes place, and native methods are linked from the dynamic library so found.

这篇关于使用 JNI 链接静态库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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