在示例程序中找不到JNI_OnLoad_libname [英] Can't find JNI_OnLoad_libname in example program
问题描述
我究竟如何从Java调用本机静态库?我正在使用Java 8.
How exactly do I call native static libraries from Java? I'm using Java 8.
在我看来,我应该能够在具有嵌入式JVM的C ++程序中定义JNI_OnLoad_library,但是当我调用System.loadLibrary时,我的VM一直在崩溃.以下仅打印来自主打招呼".
It looks to me like I should be able to define a JNI_OnLoad_library in a C++ program with an embedded JVM but my VM keeps dying when I call System.loadLibrary. The following only prints "Hello from main".
main.cpp:
#include <jni.h>
#include <iostream>
extern "C" {
JNIEXPORT jint JNI_OnLoad_hello(JavaVM *vm, void *reserved) {
std::cout << "Hello World" << std::endl;
return JNI_VERSION_1_8;
}
}
int main(int argc, char** argv) {
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
jint error;
JavaVMOption* options = new JavaVMOption[argc-1];
for(int i = 0;i < argc-1;i++) {
options[i].optionString = argv[i+1];
}
vm_args.nOptions = argc-1;
vm_args.options = options;
vm_args.version = JNI_VERSION_1_8;
JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
jclass cls = env->FindClass("Main");
jclass stringCls = env->FindClass("java/lang/String");
jmethodID mid = env->GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
jobjectArray mainArgs = env->NewObjectArray(0, stringCls, NULL);
env->CallStaticVoidMethod(cls, mid, mainArgs);
jvm->DestroyJavaVM();
}
Main.java:
Main.java:
class Main {
public static void main(String[] args) {
try {
System.out.println("Hello from main");
System.loadLibrary("hello");
System.out.println("Hello after main");
} catch (Exception e) {
e.printStackTrace();
}
}
}
推荐答案
通过将--export-dynamic传递给链接器,我终于能够使JVM找到JNI_OnLoad_hello.这允许共享库通过在可执行文件中查找符号来解析它们.同样,System.loadLibrary引发了我怀疑的UnsatisfiedLikeErrors,但是由于某种原因,我不得不使用CheckException和DescribeException在JNI中处理它们.
I was finally able to get the JVM to find JNI_OnLoad_hello by passing --export-dynamic to the linker. This allows shared libraries to resolve symbols by looking for them in the executable. Also, System.loadLibrary was throwing UnsatisfiedLikeErrors like I suspected but for some reason I have to handle them in JNI using CheckException and DescribeException.
这篇关于在示例程序中找不到JNI_OnLoad_libname的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!