標籤:參數 code RoCE return bsp http pac .cpp 動態庫
1、準備jar
網上下載jar檔案,這裡使用的是jna-4.0.0.jar、jna-platform-4.0.0
2、建立dll
使用Visual Studio 2017建立dll(動態庫)
#define __MAIN_H__#include <windows.h>#ifdef BUILD_DLL#define DLL_EXPORT __declspec(dllexport)#else#define DLL_EXPORT __declspec(dllimport)#endif#ifdef __cplusplusextern "C"{#endif extern "C" __declspec(dllexport) int add(int a, int b); extern "C" __declspec(dllexport) int factorial(int n); extern "C" __declspec(dllexport) char* say(char* msg); extern "C" __declspec(dllexport) bool sayno(bool flag);#ifdef __cplusplus}#endif#endif // __MAIN_H_
// Dll3.cpp : 定義 DLL 應用程式的匯出函數。//#include "stdafx.h"int add(int a, int b) { return a + b;}int factorial(int n) { int i; int r = 1; for (i = 1; i < n + 1; i++) r = r * i; return r;}char* say(char* msg) { return msg;}bool sayno(bool flag) { return !flag;}BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved){ switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process // return FALSE to fail DLL load break; case DLL_PROCESS_DETACH: // detach from process break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_THREAD_DETACH: // detach from thread break; } return TRUE; // succesful}
3、建立Java項目調用dll
package jna;import com.sun.jna.Library;import com.sun.jna.Native;public class Test { interface Dll3 extends Library { Dll3 INSTANCE = (Dll3) Native.loadLibrary("Dll3",Dll3.class); public int add(int a,int b); public int factorial(int n); public String say(String msg); public boolean sayno(boolean flag); } public static void main(String[] args) {// System.out.println(System.getProperty("java.version"));// System.out.println(System.getProperty("sun.arch.data.model")); Dll3 clib = Dll3.INSTANCE; System.out.println("測試返回結果:"+clib.add(13, 13)); System.out.println("測試返回結果:"+clib.factorial(1)); System.out.println("測試返回結果:"+clib.say("heoll wrold!!")); System.out.println("測試返回結果:"+clib.sayno(true)); }}
4、出現的問題
Exception in thread "main" java.lang.UnsatisfiedLinkError: Error looking up function
導致這個問題出現的又很多原因基本上dll上引起的,檢查函數名是否正確、檢查參數是否正確、
extern "C" __declspec(dllexport)這個得加上要不然只是編譯成功了dll,dll是不完整的。
這幾個因素也可能導致失敗!編譯的dll和對應的jdk是64位還是32位。
Java 使用 JNA 調 dll