让我们看下面的代码
public class SomeClass {
public OtherClass method(final String param1,final String param2){
AnotherClass obj1 = AnotherClass.getInstance();
return obj.instanceMethod(new YetAnotherClass<OtherClass>() {
@Override
public OtherClass run() {
return OtherClass.get(param1, param2);
}
});
}
}
我的问题是有什么方法可以通过 JNI 在 C/C++ 中实现接口(interface),而无需在 Java 中创建 native 方法?
最佳答案
一个选项是 Java Native Access (JNA) 库。查看其项目页面 JNA .我引用它的项目站点:
JNA provides Java programs easy access to native shared libraries without writing anything but Java code - no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes.
下面的例子来自项目的toturial page演示如何使用它从定义函数的 native 库调用 printf
函数:
package com.sun.jna.examples;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
/** Simple example of JNA interface mapping and usage. */
public class HelloWorld {
// This is the standard, stable way of mapping, which supports extensive
// customization and mapping of Java to native types.
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary)
Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"),
CLibrary.class);
void printf(String format, Object... args);
}
public static void main(String[] args) {
CLibrary.INSTANCE.printf("Hello, World\n");
for (int i=0;i < args.length;i++) {
CLibrary.INSTANCE.printf("Argument %d: %s\n", i, args[i]);
}
}
在 Windows 上,printf
函数在 msvcrt.dll
中定义,示例加载该 DLL 并从中调用该函数。
JNA 项目很成熟,根据它的网页,它有一些非常有名的用户。
需要指出的是,JNA 本身在底层使用 JNI,但在大多数情况下,您不需要自己使用 JNI。因此,您可以专注于在 C 中实现您的 native 代码(创建您自己的 DLL 或共享库文件),然后使用 JNA 在 Java 中加载它们。
关于java - 如何在 C 中实现 Java 接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40647656/