Kotlin 是否在底层使用与 Java 相同的 native 接口(interface)实现? 它与 Java 一样高效(或低效)吗(对象传输、字节流等的成本)?
最佳答案
在底层,实现是相同的,因为它将转换为相同的 Java 代码。这意味着它与您的 Java 代码一样高效。
给定这个具有 native 方法 nativeMethod()
的 Kotlin 类:
class ExampleJni {
companion object {
init {
System.loadLibrary("example-jni")
}
}
external fun nativeMethod(): String
}
它将使用该 Java 类的“相同”实现(转换并不完全相同,但不会影响 native 实现):
public class ExampleJni {
static {
System.loadLibrary("hello-jni");
}
public final native String nativeMethod();
}
编辑
更清楚地了解转换。如果反编译 Kotlin 代码,您可以看到它被转换为两个类。 第一个包含 native 方法:
@dalvik.annotation.MemberClasses
@kotlin.Metadata
public final class ExampleJni {
public static final ExampleJni$Companion Companion;
public ExampleJni() { ... }
static void <clinit>() { ... }
@org.jetbrains.annotations.NotNull
// Here you can see that the implementation is the same.
public final native String nativeMethod() { ... }
}
另一个是与伴生对象
相关的内部类。
@dalvik.annotation.EnclosingClass
@dalvik.annotation.InnerClass
@kotlin.Metadata
public final class ExampleJni$Companion {
private ExampleJni$Companion() { ... }
public ExampleJni$Companion(DefaultConstructorMarker) { ... }
}
关于java-native-interface - Kotlin 原生接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46648121/