简体   繁体   English

带有静态库的JNI:不满意的链接错误

[英]JNI with static library: unsatisfied link error

I've built a static library with g++: 我用g ++建立了一个静态库:

g++-5 main.cpp -fPIC -Wall -std=c++11 -lboost_system ......

Now I want to call its methods via JNI: 现在,我想通过JNI调用其方法:

public static void main(String[] args) {
    System.load("/Users/XXX/example/libjnidb4java.a");
    JNIDB db = new JNIDB();
    db.createTable("Name", "Dir");
  }

Turns out there's a UnsatisfiedLinkError Exception: 原来有一个UnsatisfiedLinkError异常:

Exception in thread "main" java.lang.UnsatisfiedLinkError: /Users/XXX/example/libjnidb4java.a: dlopen(/Users/XXX/example/libjnidb4java.a, 1): no suitable image found.  Did find:
    /Users/XXX/example/libjnidb4java.a: unknown file type, first eight bytes: 0x21 0x3C 0x61 0x72 0x63 0x68 0x3E 0x0A
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1937)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1822)
    at java.lang.Runtime.load0(Runtime.java:809)
    at java.lang.System.load(System.java:1086)

NOTE 注意

I tried with dynamic library, it works fine, but in my case, I need it to be static library. 我尝试使用动态库,它可以正常工作,但就我而言,我需要将其作为静态库。 I create this static library via ar -r libjnidb4java.a a.out . 我通过ar -r libjnidb4java.a a.out创建此静态库。

And I found Java 8 has already supports statically linked library here . 而且我发现Java 8 在这里已经支持静态链接库。 Like the docs say, I created a method : 就像文档所说的,我创建了一个方法:

jint JNI_OnLoad_xxxdb4java(JavaVM *vm, void *reserved) { return JNI_VERSION_1_8; }

You cannot dynamically load a static library. 您不能动态加载静态库。 You can only dynamically load a shared library. 您只能动态加载共享库。

The JNI docs you refer to talk about using JNI with static libraries, but that assumes that you've statically linked a library into the JVM. 您引用的JNI文档讨论了将JNI与静态库一起使用,但是假设您已将库静态链接到JVM。 So if you really must use a static library then you're going to have to rebuild your own JVM which sounds like an unenviable experience. 因此,如果您确实必须使用静态库,那么您将不得不重建自己的JVM,这听起来像是令人羡慕的体验。

It's not clear to me why there's a difference for you between using a static library and a shared library (you are still trying to dynamically load it, after all, which screams dynamic library to me) but I would try to overcome that limitation first. 我尚不清楚为什么在使用静态库和共享库之间会有区别(毕竟,您仍在尝试动态加载它,这对我来说是动态库),但我会首先尝试克服该限制。

If you want to create a single installable unit for your users, then what you want is to create a single shared library of your own. 如果要为用户创建单个可安装单元,那么您要创建自己的单个共享库。 Your library should then statically link its dependencies so that they are included in your library. 然后,您的库应静态链接依赖项,以便它们包含在您的库中。 You can then use loadLibrary on that single unit without worrying about dependencies being installed. 然后,您可以在单个单元上使用loadLibrary ,而不必担心安装依赖项。

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

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