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