Jni of linux platform

xiaoxiao2021-02-28  122

linux下使用JNI小记,网上有很多例子,但在我理解的基础上小记一下:

step 1: 首先,编写你的java程序,但要在静态初始化列表中 load你要使用的动态库,注意去掉动态库的lib以及.so后缀名。

import java.util.*; import java.io.*; public class Student { private String name; private int id; private int score; public Student(String name,int id,int score) { this.name = name; this.id = id; this.score = score; } public native String getStudentInfo(String name,int id,int score); static { System.loadLibrary("StuUtil"); } public static void main(String[] args) { if(args.length!=3) { System.out.println("wrong information about this student..."); return; } Student stu = new Student(args[0],Integer.valueOf(args[1]),Integer.value> System.out.println("information:\n"+stu.getStudentInfo(stu.name,stu.id,stu.score)); }

因为你load的library是“StuUtil”,所以你的动态库应该是libStuUtil.so;

step 2: 在命令行上编译该java文件,即运行:javac Student.java step 3: 生成动态库的header文件,运行命令:javah -jni Student step 4:在同一路径下创建.cpp 文件,并编写你需要的功能

#include<stdio.h> #include"Student.h" JNIEXPORT jstring JNICALL Java_Student_getStudentInfo (JNIEnv *env, jobject obj, jstring name, jint id, jint score) { char str[30]; const jbyte *cname = (const jbyte *)env->GetStringUTFChars(name, JNI_FALSE ); sprintf(str,"name:%s\nid:%d\nscore:%d",cname,id,score); env->ReleaseStringUTFChars(name, (const char *)cname ); return env->NewStringUTF(str); }

step 5 编译生成共享库,首先你需要找到你的java jdk的位置,然后运行以下命令: gcc -I/home/jbuilder/jdk1.3.1/include -I/home/jbuilder/jdk1.3.1/include/linux -fPIC -c Student.cpp 接着生成 Student.o文件,运行以下命令: gcc -shared -Wl,-soname,libStuUtil.so.1 -o libStuUtil.so.1.0 Student.o 接下来将生成的共享库拷贝为标准文件名 cp libStuUtil.so.1.0 libStuUtil.so

step 6 最后通知动态链接程序此共享文件的路径,运行以下命令 export LD_LIBRARY_PATH=‘pwd’:$LD_LIBRARY_PATH

总结,然后你就可以调用JNI方法了。

转载请注明原文地址: https://www.6miu.com/read-84439.html

最新回复(0)