如何從jar中載入.so
阿新 • • 發佈:2020-12-19
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