1、導入JNA包:
<dependency>
<groupId>com.sun.jna</groupId>
<artifactId>jna</artifactId>
<version>3.0.9</version>
</dependency>
2、寫一個接口CEnDeCheckLib繼承Library類,此接口中即可撰寫C++動態庫的方法。
3、使用下述方法加載動態庫的實例:libraryPath爲動態庫中.dll文件(windows平臺下的使用的動態庫文件)或.so(linux平臺下使用的動態庫文件)文件存儲的位置
CEnDeCheckLib instance = (CEnDeCheckLib) Native.loadLibrary(libraryPath, CEnDeCheckLib.class);
4、使用instance 調用動態庫的方法。
注意:調用動態庫傳參時有坑:
java中一般字符串類型設置爲String,當屬性無值時,默認爲null,如果把null傳給動態庫方法,idea運行項目會突然停止,且報出如下錯誤:
#
# A fatal error has been detected by the Java Runtime Environment:
#
# EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x00007fff4371669a, pid=4432, tid=0x0000000000003a64
#
# JRE version: Java(TM) SE Runtime Environment (8.0_191-b12) (build 1.8.0_191-b12)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.191-b12 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C [endecheck.dll+0x3669a]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# E:\work\git\gis-lss-map-license-management-80003819\app-license-parent\hs_err_pid4432.log
#
# If you would like to submit a bug report, please visit:
# http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
傳給動態庫方法的字符串參數如無值時,需傳入空的字符串"",不能傳入null,爲解決此問題,可將java的String屬性對應的默認值修改爲"",如
String result = ""