gpt4 book ai didi

带有变量的 Java 加载库

转载 作者:行者123 更新时间:2023-11-30 08:40:56 24 4
gpt4 key购买 nike

我正在尝试使用 System.load() 函数和变量加载库。当我在每个函数中加载库时它会起作用,但我希望能够通过一个常规系统加载来完成它,类似于您在使用已知库路径加载时所做的事情。

    static{
System.load("/libraryPath/libLibrary.so");
}

但是,无法为该 System.load 提供静态变量,因为它不会在调用加载时实例化。有任何想法吗?谢谢

编辑

我找到了解决办法,我最终在不同的类中使用了静态 setter/getter 。这样做的好处是我可以解析存储位置的配置文件。存储变量,并在我需要库的情况下使用类中的静态方法检索它。现在我可以像这样进行一般加载:

    static{
System.load(OtherClass.getLibrary());
}

谢谢大家的帮助

最佳答案

这是我在任何地方都用来加载 native 代码的代码。希望对您有所帮助。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class NativeLoader {

/** Directory containing native libraries */
private static final String NATIVE_LIBS_DIRECTORY = "/native/";

/** Extension for temporary file containing extracted native library */
private static final String TEMPORARY_FILE_EXT = ".tmp";

/**
* Loads a native library
*
* @param libraryName
* name of the native library to load
* @throws IOException
* if the native library cannot be loaded
*/
public static void loadEmbeddedLibrary(String libraryName) throws IOException {

String mapName = System.mapLibraryName(libraryName);
InputStream is = NativeLoader.class.getResourceAsStream(NATIVE_LIBS_DIRECTORY + mapName);

if (is != null) {
File native_library = File.createTempFile(mapName, TEMPORARY_FILE_EXT);
native_library.deleteOnExit();
native_library.setWritable(true);
native_library.setExecutable(true);

if (native_library.exists()) {
FileOutputStream os = new FileOutputStream(native_library);
int read;
byte[] buffer = new byte[4096];
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
os.close();
is.close();

System.load(native_library.getPath());
}
else {
is.close();
}
}
}
}

关于带有变量的 Java 加载库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com