【发布时间】:2020-03-22 23:58:45
【问题描述】:
我有一个带有 two simple implementations 的回购协议,用于使用 C/C++ 的 JNI。
我有 C++ 静态 JNI 方法的 java.lang.UnsatisfiedLinkError 错误。
(base) GlushenkovYuri:java y.glushenkov$ /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/bin/java -Djava.library.path=. MyJNIExample
Hello World from C!
Exception in thread "main" java.lang.UnsatisfiedLinkError: MyJNIExample.sayHelloCpp()V
at MyJNIExample.sayHelloCpp(Native Method)
at MyJNIExample.main(MyJNIExample.java:51)
但对于 C 本机方法,相同的方法也可以很好地工作。
对于没有 static 的 C++ 工作。
您可以通过以下方式重现相同的行为:
1) 用the static native method for C++ 和this one 取消注释行。并用the NON static native method for C++ 和this one 注释行;
2) 只需执行我的README.md 文件中描述的后续步骤即可;
有人可以向我解释为什么原生方法静态/非静态适用于 C,但只有原生非静态方法适用于 C++?
UPD:我的header 文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class MyJNIExample */
#ifndef _Included_MyJNIExample
#define _Included_MyJNIExample
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: MyJNIExample
* Method: sayHelloC
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_MyJNIExample_sayHelloC
(JNIEnv *, jclass);
/*
* Class: MyJNIExample
* Method: sayHelloCpp
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_MyJNIExample_sayHelloCpp
(JNIEnv *, jclass);
#ifdef __cplusplus
}
#endif
#endif
【问题讨论】:
-
发布生成的头文件,这样人们就不必自己生成了。请注意,静态本机方法将接收
jclass作为其第二个参数,而不是jobject。 -
无法在带有 Java 1.8.0_66 的 MacOS 10.14.6 上重现。您是否不小心在 .cpp 文件
static中创建了 C++ 函数?这将从链接器中隐藏它。 -
或者你是否去掉了
extern "C"标签? -
@Michael 我已经更新了我的仓库,我添加了头文件。 github.com/Arxemond777/JNI_C_CPP_example/blob/master/src/main/…
-
@Botje 不,我做到了。我的 .cpp 文件和我的仓库一样。 github.com/Arxemond777/JNI_C_CPP_example/blob/master/src/main/…
标签: java c++ c java-native-interface