jni初试

springboot环境下java调用c程序生成动态链接库(基于JNI,linux环境下运行)

本文根据:
https://blog.csdn.net/qq_28483283/article/details/90259838
并结合自己的实践修改。

第一部分:简单的java调用C程序demo(在别人的基础上修改解释)

第一步.首先,我们先写个JAVA类:

public class HelloJNI {
    
    static {
        System.loadLibrary("HelloWorld");  //链接库的名字
    }
    
    public native static void setNum(int num);  //链接库的方法
    public native static int get();//链接库的方法
    
    public static void main(String[] args) {
        HelloJNI test = new HelloJNI(); //声明对象的时候,回去执行static里面的方法,加载c程序库
        test.setNum(666);
        System.out.println(test.get());
    }
}

解释1:System.loadLibrary(“HelloWorld”);这句话是在执行java代码之前加载动态库,大家可以查阅一下System.loadLibrary的用法,System.load其实也是可以的,其中二者区别为:
System.load参数必须为库文件的绝对路径,可以是任意路径
System.loadLibrary 参数为库文件名,不包含库文件的扩展名。
上面代码写的是System.loadLibrary(“HelloWorld”);,意思就是生成的动态库文件名为HelloWorld.so(这是linux环境)(如果是window环境,则为HelloWorld.dll)
这里可能有人就会问,这个HelloWorld.so文件应该放在哪里呢?
这个需要放到linux系统下的JNI环境中,也就是说必须声明一个环境变量,对应一个文件夹,然后这个HelloWorld.so文件就放在这个文件夹下面就可以找到了。
环境变量声明:

# 查看LD_LIBRARY_PATH环境变量
echo $LD_LIBRARY_PATH

# 如果没有,则添加环境变量
# 编辑/etc/profile文件
vim /etc/profile

# 在文件的后面添加下面的环境变量,之后生成的so文件会放在这个文件夹下
export LD_LIBRARY_PATH=/home/test/nativeTest

# 让配置文件生效
source /etc/profile

在这里插入图片描述

解释2:

public native static void setNum(int num); //链接库的方法
public native static int get(); //链接库的方法

这两个方法是在这里声明,然后再c程序里面实现的方法,用native 关键字修饰即可

第二步:生成.h文件

javac HelloJNI.java 生成.class文件,为了后面执行所用
javah -jni HelloJNI生成.h文件,是为了链接c程序所用
来看一眼.h文件里面是什么吧

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

#ifndef _Included_HelloJNI
#define _Included_HelloJNI
#ifdef __cplusplus
extern "C" {
#endif
/*

 * Class:     HelloJNI
 * Method:    setNum
 * Signature: (I)V
   */
   JNIEXPORT void JNICALL Java_HelloJNI_setNum
     (JNIEnv *, jclass, jint);

/*

 * Class:     HelloJNI
 * Method:    get
 * Signature: ()I
   */
   JNIEXPORT jint JNICALL Java_HelloJNI_get
     (JNIEnv *, jclass);

#ifdef __cplusplus
}
#endif
#endif

在这里插入图片描述

第三步:编写.c程序

添加一个HelloWorld.c文件,并添加如下代码。

#include "HelloJNI.h"
int result=888;
//注:JAVA的类型跟C的类型转换 可以用JNI来操作
//有点类似继承的样子  
JNIEXPORT void JNICALL Java_HelloJNI_setNum(JNIEnv * env, jclass jc, jint num){
    result+=num;
}

JNIEXPORT jint JNICALL Java_HelloJNI_get(JNIEnv * env, jclass jc){
    return result;

}

特别需要注意的地方,.h文件和.c的文件名可以不一样,但是.h文件里面生成的方法名要和.c里面的是一样的!!!!!
也就是.h里面的方法名为Java_HelloJNI_setNum.c文件里面的方法名也需要是Java_HelloJNI_setNum
当然这个只是在同一个文件夹的情况下是这样的,如果.java文件和生成的.so文件不在同一个文件夹下面,比如java文佳在com.huali.util文件夹下面,则这个c程序的方法名应该是Java_com_huali_util_HelloJNI_setNum,不然就会报错

c程序需要引入.h文件,就是我们用java文件生成的h文件

#include "HelloJNI.h"

第四步:生成.so文件

执行命令

gcc -fPIC -I $JAVA_HOME/include -I $JAVA_HOME/include/linux -shared -o libHelloWorld.so HelloWorld.c

JAVA_HOMElinux下配置的环境变量也就是java的安装的路径,如果没有配置 JAVA_HOMElinux下的环境变量,也就是java的安装的路径,也可以直接写绝对路径。
然后替换$JAVA_HOME,变成:

gcc -fPIC -I /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.302.b08-0.el7_9.x86_64/include -I /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.302.b08-0.el7_9.x86_64/include/linux -shared -o libHelloWorld.so HelloWorld.c

然后发现几个文件都在一个文件夹下

在这里插入图片描述

.so文件放入之前设置的环境变量的目录中,运行先前生成的.class文件就可以看到结果了

mv libHelloWorld.so /home/test/nativeTest

java HelloJNI 

在这里插入图片描述

第二部分:融合到项目中

上面的demo很简单,但是如果放置到项目中,有两个弊端

第一:这个生成的.so文件还要放在特定的文件中,那用springboot每次打包,还要去关心这个东西,如果能直接将这个so文件放在项目中,一起打包,不用配置环境变量,那样就好了
第二:这个so的动态库,每次调用的时候都要去加载,那样就太浪费性能了吧,能不能在项目启动的时候就去加载,后面就不用加载了

第一步:创建springboot项目,写一个java文件,里面声明c程序里面实现的方法

本人的项目目录如下,工具为idea

在这里插入图片描述

package com.example.jnitest.library;

public class CDemo {
    public static native String mde(String param);

    public static String calculation(String param) {
        String result = mde(param);
        return result;
    }
}

我的方法名字是mde,包是com.example.jnitest.library;,所以c程序里面的方法名必须是Java_com_example_jnitest_library_CDemo_mde
解释一下:java是固定的,_代表点,com.example.jnitest.library对应包名,CDemo代表类的名字,mde是方法名,如果java文件在其他的包里面,命名就要发生相应的变化,具体参考连接:

第二步:生成.h文件,及编写c程序

1、打开windowsidea控制台,将目录切换到src下。

由于javah以后生成的.h文件需要包名+类名,所以必须在包括全包名的目录下执行javah命令,也就是项目\src\在或者项目\bin\classe\下执行 javah包名.类名的命令,若为设置classpath及切换目录,则会报找不到class文件的错误。

# 生成.class文件
javac CDemo.java

# 设置classpath
set classpath=d:\IdeaProjects\jnitest\src\main\java

# 切换到项目中的src目录
cd D:\IdeaProjects\jnitest\src

# 执行生成.h文件的命令
javah -jni com.example.jnitest.library.CDemo

在这里插入图片描述

编写.c文件,内容为,这里直接返回参数内容。

#include "com_example_jnitest_library_CDemo.h"

JNIEXPORT jstring JNICALL Java_com_example_jnitest_library_CDemo_mde
  (JNIEnv * env, jclass jc, jstring param){
  return param;
  }

第三步: 生成.so文件

.h文件和.c文件拷贝到centos环境下,运行指令,生成demo.so文件

gcc -fPIC -I /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.302.b08-0.el7_9.x86_64/include -I /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.302.b08-0.el7_9.x86_64/iclude/linux -shared -o demo.so com_example_jnitest_library_CDemo.c

在这里插入图片描述

将生成的so文件下载下来,放在项目中resource下面的native文件夹下面

在这里插入图片描述

第四步:加载项目中的so动态链接库

import java.io.*;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

/**
 * @author Sky$
 * @Description: TODO
 * @date 2018/2/8$ 17:55$
 */
public class NativeLoader {


    /**
     * 加载项目下的native文件,DLL或SO
     *
     * @param dirPath 需要扫描的文件路径,项目下的相对路径
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public synchronized static void loader(String dirPath) throws IOException, ClassNotFoundException {
        Enumeration<URL> dir = Thread.currentThread().getContextClassLoader().getResources(dirPath);
        // 获取操作系统类型
        String systemType = System.getProperty("os.name");
        //String systemArch = System.getProperty("os.arch");
        // 获取动态链接库后缀名
        String ext = (systemType.toLowerCase().indexOf("win") != -1) ? ".dll" : ".so";
        while (dir.hasMoreElements()) {
            URL url = dir.nextElement();
            String protocol = url.getProtocol();
            if ("jar".equals(protocol)) {
                JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
                JarFile jarFile = jarURLConnection.getJarFile();
                // 遍历Jar包
                Enumeration<JarEntry> entries = jarFile.entries();
                while (entries.hasMoreElements()) {
                    JarEntry jarEntry = entries.nextElement();
                    String entityName = jarEntry.getName();
                    if (jarEntry.isDirectory() || !entityName.startsWith(dirPath)) {
                        continue;
                    }
                    if (entityName.endsWith(ext)) {
                        loadJarNative(jarEntry);
                    }
                }
            } else if ("file".equals(protocol)) {
                File file = new File(url.getPath());
                loadFileNative(file, ext);
            }

        }
    }

    private static void loadFileNative(File file, String ext) {
        if (null == file) {
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File f : files) {
                    loadFileNative(f, ext);
                }
            }
        }
        if (file.canRead() && file.getName().endsWith(ext)) {
            try {
                System.load(file.getPath());
                System.out.println("加载native文件 :" + file + "成功!!");
            } catch (UnsatisfiedLinkError e) {
                System.out.println("加载native文件 :" + file + "失败!!请确认操作系统是X86还是X64!!!");
            }
        }
    }

    /**
     * @throws IOException
     * @throws ClassNotFoundException
     * @Title: scanJ
     * @Description 扫描Jar包下所有class
     */
    /**
     * 创建动态链接库缓存文件,然后加载资源文件
     *
     * @param jarEntry
     * @throws IOException
     * @throws ClassNotFoundException
     */
    private static void loadJarNative(JarEntry jarEntry) throws IOException, ClassNotFoundException {

        File path = new File(".");
        //将所有动态链接库dll/so文件都放在一个临时文件夹下,然后进行加载
        //这是应为项目为可执行jar文件的时候不能很方便的扫描里面文件
        //此目录放置在与项目同目录下的natives文件夹下
        String rootOutputPath = path.getAbsoluteFile().getParent() + File.separator;
        String entityName = jarEntry.getName();
        String fileName = entityName.substring(entityName.lastIndexOf("/") + 1);
        System.out.println(entityName);
        System.out.println(fileName);
        File tempFile = new File(rootOutputPath + File.separator + entityName);
        // 如果缓存文件路径不存在,则创建路径
        if (!tempFile.getParentFile().exists()) {
            tempFile.getParentFile().mkdirs();
        }
        // 如果缓存文件存在,则删除
        if (tempFile.exists()) {
            tempFile.delete();
        }
        InputStream in = null;
        BufferedInputStream reader = null;
        FileOutputStream writer = null;
        try {
            //读取文件形成输入流
            in = NativeLoader.class.getResourceAsStream(entityName);
            if (in == null) {
                in = NativeLoader.class.getResourceAsStream("/" + entityName);
                if (null == in) {
                    return;
                }
            }
            NativeLoader.class.getResource(fileName);
            reader = new BufferedInputStream(in);
            writer = new FileOutputStream(tempFile);
            byte[] buffer = new byte[1024];

            while (reader.read(buffer) > 0) {
                writer.write(buffer);
                buffer = new byte[1024];
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            if (in != null) {
                in.close();
            }
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            System.load(tempFile.getPath());
            System.out.println("加载native文件 :" + tempFile + "成功!!");
        } catch (UnsatisfiedLinkError e) {
            System.out.println("加载native文件 :" + tempFile + "失败!!请确认操作系统是X86还是X64!!!");
        }

    }

}

这是我在网上找的一个加载本地动态链接库的一个方法,直接调用NativeLoader.loader( “native” );即可,这样就可以实现在项目中直接调用so文件,而不需要去linux环境中配置环境变量并且在环境变量中放入库文件了!!

第五步:在项目其中文件中加载动态库,并编写测试案例

package com.example.jnitest.controller;

import com.example.jnitest.library.CDemo;
import com.example.jnitest.loader.NativeLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class DemoController {

    static {
        //根据操作系统判断,如果是linux系统则加载c++方法库
        String systemType = System.getProperty("os.name");
        String ext = (systemType.toLowerCase().indexOf("win") != -1) ? ".dll" : ".so";
        if(ext.equals(".so")) {
            try {
                // native就是resource下面的文件夹的名称
                NativeLoader.loader( "native" );
            } catch (Exception e) {
                System.out.println("加载so库失败");
            }
            // System.loadLibrary( "v2xalgo" );
        }
    }

    @RequestMapping("test")
    public String test() {
        // 调用测试当然也可以直接调用mde接口
        return CDemo.calculation("测试:");
    }
}

NativeLoader.loader( “native” );native就是resource下面的文件夹的名称

这样就可以解决一次加载,后面就不用重复加载的问题了(这个启动文件,springboot+springcloud中必须有的启动文件)

第六部:打包项目并测试

springboot项目路打包上传到centos系统中,调用test方法验证测试:

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值