關於JAVA呼叫C++的幾種方式和一些問題 UnsatisfiedLinkError
阿新 • • 發佈:2019-01-01
關於JAVA呼叫C++的幾種方式和一些問題
java呼叫c++有幾種方式,1.JNA方式,2,JNative 方式,3.JNI 方式。:
1.JNA方式
public interface MyCLibrary extends Library {
MyCLibrary INSTANCE =(MyCLibrary)Native.loadLibrary("Image", MyCLibrary.class);
WString Preprocess( WString inputStr);
int add(int a,int b);
}
Image.dll 位於src 根目錄下
然後在MainFrame中處理
public static void main(String[] args) {
MainFrame frame = new MainFrame();
frame.setVisible(true);
//WString 可以傳中文
WString wPStr = new WString("123qqq你好");
WString newPStr = (WString)MyCLibrary .INSTANCE.Preprocess(wPStr);
System.out .println("newPath =="+newPStr );
int result = MyCLibrary.INSTANCE.add(3,5);
System.out.println("result =="+result);
}
下面是生成DLL的C++程式程式碼:
#include "stdafx.h"
extern "C" __declspec(dllexport) wchar_t* Preprocess(wchar_t* inputStr) ;
extern "C" __declspec(dllexport) int add(int a, int b);
wchar_t* Preprocess(wchar_t* inputStr) {
return inputStr;
}
int add(int a, int b) {
return a + b;
}
wchar_t* 對應java中的WString
MyCLibrary 的函式
WString Preprocess( WString inputStr);
int add(int a,int b);
和C++ 的函式 對應
wchar_t* Preprocess(wchar_t* inputStr) {
return inputStr;
}
int add(int a, int b) {
return a + b;
}
最後java的main函式呼叫即可,返回結果為8
int result = MyCLibrary.INSTANCE.add(3,5);
常見錯誤
1.宣告函式一定要是 extern “C” __declspec(dllexport) 不然會報錯 Exception in thread “main” java.lang.UnsatisfiedLinkError: Error looking up function ‘Preprocess’: 找不到指定的程式。
2.Exception in thread “main” java.lang.UnsatisfiedLinkError: 找不到指定的模組 .C++生成DLL版本的問題,升級vs版本2010 到2015
注意:如果一直報錯誤Error looking up function ‘Preprocess’: 找不到指定的程式。 進行如下操作:
1.建立一個新的C++的DLL工程 :使用預設的
include “stdafx.h”
2.再複製下面語句,不要包含標頭檔案:
extern "C" __declspec(dllexport) wchar_t* Preprocess(wchar_t* inputStr) ;
extern "C" __declspec(dllexport) int add(int a, int b);
wchar_t* Preprocess(wchar_t* inputStr) {
return inputStr;
}
int add(int a, int b) {
return a + b;
}