JNI、JNA 入門教程
一、JNI 入門教程
1.編寫java測試類
package com.liu.jni;
public class JNILibrary {
public native static void show();
public native static int calc(int a, int b);
static {
System.loadLibrary("libshared_jni");
}
}
package com.liu.jni;
public class JNITest {
public static void main(String[] args) {
JNILibrary.show();
System.out.println(JNILibrary.calc(3, 5));
}
}
2.利用java類生成C標頭檔案
cmd進入class檔案根目錄:
cd D:\jps-workspace\jni_jna\target\classes
執行命令:
javah -classpath . -jni com.liu.jni.JNILibrary
重新命名com.liu.jni.JNILibrary.h為JNILibrary.h
3.編譯生成C++動態庫
建立動態庫project:
複製JNILibrary.h到C++動態庫project:
JNILibrary.h程式碼:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_liu_jni_JNILibrary */
#ifndef _Included_com_liu_jni_JNILibrary
#define _Included_com_liu_jni_JNILibrary
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_liu_jni_JNILibrary
* Method: show
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_liu_jni_JNILibrary_show
(JNIEnv *, jclass);
/*
* Class: com_liu_jni_JNILibrary
* Method: calc
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_liu_jni_JNILibrary_calc
(JNIEnv *, jclass, jint, jint);
#ifdef __cplusplus
}
#endif
#endif
JNIShared.cc程式碼:
#include <iostream>
#include "JNILibrary.h"
using namespace std;
JNIEXPORT void JNICALL Java_com_liu_jni_JNILibrary_show(JNIEnv *, jclass) {
cout << "JNI Shared Library." << endl;
}
JNIEXPORT jint JNICALL Java_com_liu_jni_JNILibrary_calc(JNIEnv *, jclass,
jint a, jint b) {
return a + b;
}
然後編譯生成動態庫:
4.新增動態庫到jni_jna
複製libshared_jni.dll到jni_jna工程目錄
然後設定動態庫位置:
5.測試JNITest
二、JNA入門教程
1.編寫java測試類
package com.liu.jna;
import com.sun.jna.Library;
import com.sun.jna.Native;
public interface JNALibrary extends Library {
JNALibrary INSTANCE = (JNALibrary) Native.loadLibrary("libshared_jna", JNALibrary.class);
void show();
int calc(int a, int b);
}
package com.liu.jna;
public class JNATest {
public static void main(String[] args) {
JNALibrary.INSTANCE.show();
System.out.println(JNALibrary.INSTANCE.calc(3, 5));
}
}
2.編譯生成C++動態庫
建立動態庫project同上
JNAShared.cc程式碼:
#include <iostream>
using namespace std;
extern "C" __declspec(dllexport) void show();
extern "C" __declspec(dllexport) int calc(int a, int b);
void show() {
cout << "JNA Shared Library." << endl;
}
int calc(int a, int b) {
return a + b;
}
然後編譯生成動態庫:
3.新增動態庫到jni_jna
複製libshared_jna.dll到jni_jna工程目錄
4.測試JNATest
例項原始碼: