java-native-interface - Kotlin 原生接口(interface)

标签 java-native-interface kotlin

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/

相关文章:

android - 我的 Android 应用程序突然关闭

c++ - eclipse 可以使用像 cocos2d 这样的外部库来自动完成吗?

android - 如何在 Horizo​​ntal RecyclerView 中最后显示部分项目以指示滚动?

android - 如何在 viewpager 中使用 webview 的水平滚动?

java - 将 kotlin 与 spring-boot 一起使用时,启用 Hystrix 会导致 NullPointerException

java - 如何将 Java 对象类型(如 Long 和 Integer)转换为原始类型(如 long 和 int)

java - Android JNI : SIGSEGV on CallObjectMethod

java - jni本地方法问题

flutter - 从 2.8.1 升级到 Flutter 3.0,得到 : Warning: Operand of null-aware operation '?.' has type 'PaintingBinding' which excludes null error

gradle - 如何从 Gradle 中运行 Kotlin-Script (*.kts) 文件?