我一直在阅读 Panama Project最近。
我知道它将成为 JNI 的下一代替代品 - 它将允许 Java 开发人员使用 Java 在 native 层上进行编码(恕我直言,这真是太棒了)。
使用 jnr-posix 可以看出用法很简单,例如:
public class FileTest {
private static POSIX posix;
@BeforeClass
public static void setUpClass() throws Exception {
posix = POSIXFactory.getPOSIX(new DummyPOSIXHandler(), true);
}
@Test
public void utimesTest() throws Throwable {
// FIXME: On Windows this is working but providing wrong numbers and therefore getting wrong results.
if (!Platform.IS_WINDOWS) {
File f = File.createTempFile("utimes", null);
int rval = posix.utimes(f.getAbsolutePath(), new long[]{800, 200}, new long[]{900, 300});
assertEquals("utimes did not return 0", 0, rval);
FileStat stat = posix.stat(f.getAbsolutePath());
assertEquals("atime seconds failed", 800, stat.atime());
assertEquals("mtime seconds failed", 900, stat.mtime());
// The nano secs part is available in other stat implementations. We really just want to verify that the
// nsec portion of the timeval is passed through to the POSIX call.
// Mac seems to fail this test sporadically.
if (stat instanceof NanosecondFileStat && !Platform.IS_MAC) {
NanosecondFileStat linuxStat = (NanosecondFileStat) stat;
assertEquals("atime useconds failed", 200000, linuxStat.aTimeNanoSecs());
assertEquals("mtime useconds failed", 300000, linuxStat.mTimeNanoSecs());
}
f.delete();
}
}
// ....
// ....
// ....
}
我的问题是 - 使用 JNI 并知道它有多么麻烦,是否有将现有 JNI 解决方案移植到巴拿马格式的解决方案?
IE - 检查生成的(通过弃用的 javah)C 头文件和头文件的 C 实现,确定可以由 Panama API 替换的函数,然后生成 java 输出文件?
或者现有的 JNI 解决方案是否需要手动重构?
附加链接:
最佳答案
JNI格式如下:
Java -> JNI glue-code library -> Native code
巴拿马项目的目标之一是移除这个中间层并获得:
Java -> Native code
思路是可以使用命令行工具处理一个原生的头文件(.h
)生成调用原生代码的Java接口(interface),JDK代码会完成剩下的工作在运行时将两者连接在一起。
如果您当前的 JNI 代码在此胶合代码层中做了很多事情,那么在移植到巴拿马时可能必须在 Java 端重新编写这些代码。 (这取决于使用的接口(interface)提取工具可以自动完成多少)。
但是如果您使用的是 JNA 或 JNR 之类的东西,那么迁移到巴拿马应该相对容易,因为这 2 个具有非常相似的 API,您也可以在其中将接口(interface)绑定(bind)到本地库。
但是这样的问题:
will there be a solution for porting existing JNI solutions to the Panama format?
很难回答,因为没有人能预测 future 。我觉得 panama 和 JNI 之间有足够多的差异,这两者之间的自动 1 对 1 转换可能是不可能的。尽管如果您的胶水代码除了转发参数之外没有做太多事情,那么接口(interface)提取工具可能会为您完成所有工作。
如果您有兴趣,可以查看最近开始发货的巴拿马抢先体验版本:https://jdk.java.net/panama/
或者观看最近关于它的讨论:https://youtu.be/cfxBrYud9KM
关于Java 10 巴拿马项目 - 将 JNI 解决方案移植到巴拿马,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49972859/