Jni of linux platform

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方法了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值