第一步:編寫Java端代碼
定義一個Java類
public class TestNativeDemo {
// 聲明本地方法
public native String testJni(String arg);
static {
// 加載DLL文件
System.loadLibrary("TestNativeDemoCPP");
}
public static void main(String args[]) {
TestNativeDemo ob = new TestNativeDemo();
// 調(diào)用本地方法
String result = ob.testJni("Hello,Jni"); // call a native method
System.out.println("TestNativeDemo.testJni=" + result);
}
}
// 聲明本地方法
public native String testJni(String arg);
static {
// 加載DLL文件
System.loadLibrary("TestNativeDemoCPP");
}
public static void main(String args[]) {
TestNativeDemo ob = new TestNativeDemo();
// 調(diào)用本地方法
String result = ob.testJni("Hello,Jni"); // call a native method
System.out.println("TestNativeDemo.testJni=" + result);
}
}
----------------------------------------------
編譯之后在生成TestNativeDemo.class的bin目錄下執(zhí)行javah TestNativeDemo命令生成頭文件TestNativeDemo.h
----------------------------------------------
/* DO NOT EDIT THIS FILE - it is machine generated */sky7034
#include <jni.h>
/* Header for class TestNativeDemo */
#ifndef _Included_TestNativeDemo //避免重復(fù)包含頭文件
#define _Included_TestNativeDemo
#ifdef __cplusplus //c++編譯環(huán)境中才會定義__cplusplus
extern "C" { //告訴編譯器下面的函數(shù)是c語言函數(shù)(因為c++和c語言對函數(shù)的編譯轉(zhuǎn)換不一樣,主要是c++中存在重載)
#endif
/*
* Class: TestNativeDemo
* Method: testJni
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_TestNativeDemo_testJni
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
#include <jni.h>
/* Header for class TestNativeDemo */
#ifndef _Included_TestNativeDemo //避免重復(fù)包含頭文件
#define _Included_TestNativeDemo
#ifdef __cplusplus //c++編譯環(huán)境中才會定義__cplusplus
extern "C" { //告訴編譯器下面的函數(shù)是c語言函數(shù)(因為c++和c語言對函數(shù)的編譯轉(zhuǎn)換不一樣,主要是c++中存在重載)
#endif
/*
* Class: TestNativeDemo
* Method: testJni
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_TestNativeDemo_testJni
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif