JNA Java-Native-Access 調用C/C++ dll動态連結庫
- 1.架構選擇
- 1.1 JNI
- 1.2 JNative
- 1.3 JNA
- 2. JNA使用
- 2.1 pom檔案
- 2.2 建立測試類
- 2.3 資料映射
- 參考連結:
1.架構選擇
1.1 JNI
1、編寫靜态方法(用java聲明)
2、編譯生成class檔案
3、編譯生成h檔案
4、編寫C檔案(用C/C++實作)
5、配置NDK
6、配置so庫
7、在Activity調用(Java調用C/C++)。
1.2 JNative
1、下載下傳Jnative.jar,下載下傳位址如下:
http://nchc.dl.sourceforge.net/sourceforge/jnative/JNative.jar 把JNativeCpp.dll放在c:\windows\system32目錄下;把要調用的dll檔案也放在c:\windows\system32目錄下。
2、編碼調用dll
1.3 JNA
GitHub:https://github.com/java-native-access/jna 5.5版本文檔:https://java-native-access.github.io/jna/5.5.0/javadoc/overview-summary.html#loading
1、下載下傳 jna.jar,jna-platform.jar放入到java項目類路徑下;
2、建立一個接口繼承Library;
3、聲明方法,方法的傳回值和參數要和本地dll對應;
4、執行個體化接口執行個體;
5、調用接口;
2. JNA使用
2.1 pom檔案
<!-- 調用C/C++ dll動态連結庫 -->
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.5.0</version>
</dependency>
2.2 建立測試類
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class JnaTest {
// This is the standard, stable way of mapping, which supports extensive
// customization and mapping of Java to native types.
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary)
Native.load((Platform.isWindows() ? "msvcrt" : "c"),
CLibrary.class);
void printf(String format, Object... args);
}
public static void main(String[] args) {
CLibrary.INSTANCE.printf("Hello, World\n");
for (int i=0;i < args.length;i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
}
}
}
2.3 資料映射
C語言類型 | 本地表示 | Java類型 |
char | 8 位整數 | byte |
wchar_t | 與平台相關 | char |
short | 16 位整數 | short |
int | 32 位整數 | int |
int | 布爾标志 | boolean |
enum | 枚舉類型 | int (usually) |
long long, __int64 | 64 位整數 | long |
float | 32 位浮點 | float |
double | 64 位浮點 | double |
pointer (e.g. void*) | 與平台相關(32 位或 64 位指向記憶體的指針) | Buffer Pointer |
pointer (e.g. void*),array | 32 位或 64 位指向記憶體(參數/傳回)連續記憶體(結構成員)的指針 | [] (array of primitive type) |
long | 平台相關(32 位或 64 位整數) | NativeLong |
const char* | NUL 終止的陣列(本機編碼或jna.encoding) | String |
const wchar_t* | NUL 端接的陣列(單碼) | WString |
char** | C 字元串的 NULL 終止數組 | String[] |
wchar_t** | 寬 C 字元串的 NULL 終止數組 | WString[] |
void** | 空端指針數組 | Pointer[] |
struct*, struct | 指向結構(參數或傳回) (或顯式)按值 (結構成員) (或顯式)結構的指針) | Structure |
union | 與Structure | Union |
struct[] | 結構數組,在記憶體中連續 | Structure[] |
void (*FP)() | 函數指針(Java 或本機) | Callback |
pointer ( *) | 與Pointer | PointerType |
other | 整數類型 | IntegerType |
other | 自定義映射,取決于定義 |