jni

STEP1 编写java调用文件

J2C.java

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

public class J2C
{
static
{
try{
// 此处即为本地方法所在链接库名
System.loadLibrary("j2c");
} catch(UnsatisfiedLinkError e)
{
System.err.println( "Cannot load J2C library:\n " +
e.toString() );
}
}

//声明的本地方法
public static native int write2proc(int pid);

public static void main(String[] args){

//获取本进程(即主线程)的pid
final RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
final String info = runtime.getName();
final int index = info.indexOf("@");


if (index != -1) {
final int pid = Integer.parseInt(info.substring(0, index));
System.out.println(info);
System.out.println(pid);

write2proc(pid);
}


try{
Thread.sleep(8000);
} catch(InterruptedException e){
e.printStackTrace();
}
}
}

Step2 生成J2C.h

bash: javac -h ./ J2C.java

以下内容为自动生成:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class J2C */

#ifndef _Included_J2C
#define _Included_J2C
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: J2C
* Method: write2proc
* Signature: (I)I
*/
JNIEXPORT jint JNICALL Java_J2C_write2proc
(JNIEnv *, jclass, jint);

#ifdef __cplusplus
}
#endif
#endif

Step3 编写J2C.c

#include <stdio.h>

#include "J2C.h"

JNIEXPORT int JNICALL Java_J2C_write2proc(JNIEnv * env, jobject arg, jint pid)
{

printf("current pid is %d\n", pid);

return 0;

}

Step4 生成J2C.so

bash: gcc J2C.c -fPIC -shared -o libJ2C.so

利用gcc、g++编译源文件找不到jni.h头文件:

可以在编译时利用-I选项指定jni.h头文件所在目录:

gcc J2C.c -fPIC -shared -o libJ2C.so -I /usr/java/jdk-12.0.1/include/ -I /usr/java/jdk-12.0.1/include/linux/

注意:cmake make 找不到jni.h的情况,可以将文件复制到公共库/usr/include/

------ 本文结束 🎉🎉 谢谢观看 ------
0%