我在尝试使JNI工作时遇到一些问题。
我有一个C++应用程序,我想在我的Java程序中调用此应用程序中的方法。
我编写了调用本机方法的Java程序,然后使用javah
生成了头文件。将我的C++测试程序编译到库.so后,我从Java程序调用此库。可以加载System.loadLibrary,但似乎他无法在其中找到方法。我得到了:
Exception in thread "main" java.lang.UnsatisfiedLinkError: ApiPackets.get_lost_packets()V
at ApiPackets.get_lost_packets(Native Method)
at ApiPackets.main(ApiPackets.java:12)
这是我的Java调用本机方法:
public class ApiPackets {
public native void get_lost_packets();
public native int get_late_packets();
public native int get_out_of_order_packets();
static { System.loadLibrary("ApiPackets");}
public static void main(String[] args) {
ApiPackets api = new ApiPackets();
System.out.println("pass");
api.get_lost_packets();
}
}
这是我的C++,然后编译为
libApiPackets.so
:#include "ApiPackets.h"
#include <stdio.h>
#include "main_window.h"
JNIEXPORT void JNICALL Java_ApiPackets_get_lost_packets
(JNIEnv * env, jobject obj) {
printf("coucou");
return;
}
JNIEXPORT jdouble JNICALL Java_ApiPackets_get_1late_1packets
(JNIEnv * env, jobject obj) {
jdouble late = mw->priv->current_call->get_late_packets ();
return late;
}
JNIEXPORT jdouble JNICALL Java_ApiPackets_get_1out_1of_1order_1packets
(JNIEnv * env, jobject obj) {
jdouble out_of_order = mw->priv->current_call->get_out_of_order_packets ();
return out_of_order;
}
最佳答案
C++函数必须声明为extern "C"
。 (JNI宏JNIEXPORT
不会这样做,因为它被设计为在两个C语言中都使用
和C++。)