JNI 簡介
JNI 即Java Native Interface痢虹,說通俗點(diǎn)就是java端寫一個(gè)nvtive方法岩睁,由更底層的語言(c/c++)實(shí)現(xiàn)這個(gè)native方法。
業(yè)務(wù)需求:
給客戶部署我們的產(chǎn)品,需要獲取主機(jī)的唯一標(biāo)識(shí)撒穷,并且我們不希望把獲取的這個(gè)唯一標(biāo)識(shí)的相關(guān)信息暴露給客戶,所以將采集主機(jī)唯一標(biāo)識(shí)的代碼用C開發(fā)裆熙,并編譯成二進(jìn)制so文件端礼,供java調(diào)用。
step 1:編寫OsId 的類
package com.test;
public class OsId {
private static final String LIBOSID = "osid";
public native String getOsId(); //由C語言實(shí)現(xiàn)
private static OsId instance = new OsId();
private OsId() {
System.loadLibrary(LIBOSID); //會(huì)load libosid.so
}
public static String get() {
return instance.getOsId();
}
}
step 2:javac OsId.java
step 3:javah com.test.OsId
此處需要注意java類的包結(jié)構(gòu),需要將第二部編譯好的OsId.class文件入录,放到com/test/ 目錄下蛤奥,
然后在com的上一層目錄執(zhí)行javah com.test.OsId,(OsId 類的全類名)
step 4:用c語言實(shí)現(xiàn)方法
getinfo.c
#include "com_test_OsId.h"
#include <stdio.h>
#include <string.h>
char encode[128] = {'\0'};
char* getEnCode(){
FILE * fp;
fp=popen("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","r");//獲取主機(jī)唯一標(biāo)識(shí)的linux命令,后續(xù)摻雜各種算法
fgets(encode,sizeof(encode),fp);
pclose(fp);
return encode;
}
JNIEXPORT jstring JNICALL
Java_com_test_OsId_getOsId
(JNIEnv * env, jobject obj)
{
// return getinfo();
return (*env)->NewStringUTF(env, strupr(getEnCode()));
}
main()
{
printf("%s", getEnCode());
}
step 5:編譯c源碼
gcc -fPIC -shared -c getinfo.c
step 6:將打成so文件(命名規(guī)則一定是lib開頭)
gcc -fPIC -shared getinfo.o -o libosid.so