Java 10巴拿马项目 - 为巴拿马提供JNI解决方案

Ran*_*itz 5 java java-native-interface java-10 jep project-panama

我最近一直在读巴拿马项目.

我知道它将成为JNI的下一代替代品 - 它将允许Java开发人员使用Java在本机层上进行编码(这是令人惊叹的恕我直言).

从我所看到的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();
        }
    }
// ....
// ....
// ....
}
Run Code Online (Sandbox Code Playgroud)

我的问题是 - 与JNI合作,并且知道它有多繁琐,是否有解决方案将现有的JNI解决方案移植到巴拿马格式?

IE - 浏览生成的(通过弃用的javah)C头文件并在头文件的C中给出实现,识别可以被Panama API替换的函数,然后生成一个java输出文件?

或者现有的JNI解决方案是否需要手工重构?

其他链接:

Jor*_*nee 5

JNI格式如下:

Java -> JNI glue-code library -> Native code
Run Code Online (Sandbox Code Playgroud)

巴拿马项目的目标之一是移除这个中间层并得到:

Java -> Native code
Run Code Online (Sandbox Code Playgroud)

这个想法是,您可以使用命令行工具来处理本机头 ( .h) 文件以生成用于调用本机代码的 Java 接口,而 JDK 代码将在运行时完成其余的工作,只要将两者连接在一起即可。

如果您当前的 JNI 代码在此粘合代码层中做了很多事情,那么在移植到巴拿马时可能必须在 Java 端重新编写。(这取决于使用的界面提取工具可以自动完成多少)。

但是,如果您使用的是 JNA 或 JNR 之类的东西,那么迁移到巴拿马应该相对容易,因为这两个 API 非常相似,您也可以在其中将接口绑定到本机库。

但是像这样的问题:

是否有将现有 JNI 解决方案移植到巴拿马格式的解决方案?

很难回答,因为没有人可以预测未来。我觉得 panama 和 JNI 之间有足够的差异,2 之间的自动 1 对 1 转换可能是不可能的。但是,如果您的胶水代码除了转发参数之外没有做太多事情,那么界面提取工具可能会为您完成所有工作。

如果您有兴趣,可以查看最近开始发货的巴拿马早期访问版本:https : //jdk.java.net/panama/

或者观看最近的讨论:https : //youtu.be/cfxBrYud9KM