如何从jar中加载.so

java加载so在一些情况下是必须的,

如何生成so,以及在Java中调用So ,请见https://blog.csdn.net/dmw412724/article/details/81477546

 

最常见的问题是,so的加载System.load();必须是全路径的so,不能使用相对路径

打包程序最好都放在一个jar里面,如何从Jar里面加载so呢?

 

可以参考这个例子

https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo031

把so从jar中取出来,放到临时目录中,然后再加载

private String extractLibrary() {
    try {
      // Create temporary file
      File file = File.createTempFile("libHelloWorld", ".so");

      // In case it worked, we can extract lib
      if (file.exists()) {
        // First of all, let's show where do we plan to extract it
        System.out.println("Temporary file: " + file.getAbsoluteFile().toPath());

        // Now, we can get the lib file from JAR and put it inside temporary location
        InputStream link = (getClass().getResourceAsStream("/lib/libHelloWorld.so"));

        // We want to overwrite existing file. This is why we are using
        //
        // java.nio.file.StandardCopyOption.REPLACE_EXISTING
        Files.copy(
            link,
            file.getAbsoluteFile().toPath(),
            java.nio.file.StandardCopyOption.REPLACE_EXISTING);
        return file.getAbsoluteFile().toPath().toString();
      }
      // In case something goes wrong, we will simply return null
      return null;

    } catch (IOException e) {
      // The same goes for exception - we are passing null back
      e.printStackTrace();
      return null;
    }
  }

 

public class HelloWorld {

  // Location of native code will be passed from the
  // outside. In this case, Main class makes sure
  // to extract native code from JAR file
  String libFileLocation = null;

  /* This is the native method we want to call */
  public native void displayMessage();

  // In constructor we pass only location of the lib
  // file
  public HelloWorld(String lib) {
    this.libFileLocation = lib;
  }

  // This method will load native code
  // and call native method declared above
  public void callNativeMethod() {
    System.load(libFileLocation);
    displayMessage();
  }

参考

https://stackoverflow.com/questions/46609450/encapsulating-a-jni-library-inside-a-jar-file

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路边闲人2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值