Android:如何从Kotlin调用ndk函数?

时间:2016-04-29 07:51:51

标签: android android-ndk kotlin

此代码适用于Java。但是在迁移到Kotlin之后,编译器higlits方法native fun stringFromNative(): String作为错误,包含以下文本:

  

没有身体的功能必须是抽象的

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    Toast.makeText(this, stringFromNative(), Toast.LENGTH_LONG).show()
}

companion object {

    init {
        System.loadLibrary("_ndkkt")
    }
    native fun stringFromNative(): String
}
}

谢谢@KenVanHoeylandt!

Andswer是:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    Toast.makeText(this, stringFromNative(), Toast.LENGTH_LONG).show()
}

   init {
        System.loadLibrary("_ndkkt")
    }

    external fun getStringFromNative(): String
}

}

2 个答案:

答案 0 :(得分:8)

external fun stringFromNative(): String放在随播对象之外并放入MainActivity

(我通过查看https://github.com/ligee/kotlin-ndk-samples)找到答案

答案 1 :(得分:0)

Kotlin :

call method from ndk file
 external fun stringFromJNI(): String


 load c++ file
 companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }