本文介绍了Android:如何从Kotlin调用ndk函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码在Java上有效.但是在迁移到Kotlin之后,编译器将方法native fun stringFromNative(): String
视为错误,并显示以下文本:
This code works on Java. But after migration to Kotlin, compiler higlits method native fun stringFromNative(): String
as error with following text:
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!
Thanks @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
}
}
如果您希望在另一个类中使用此本机函数,则可以指定将其封闭的类,如下所示:
If you wish to use this native function in another class you can specify the class which encloses it as in:
val aStringFromNative : String = MainActivity().getStringFromNative()
推荐答案
将external fun stringFromNative(): String
放在同伴对象之外,并放入MainActivity
.
Put external fun stringFromNative(): String
outside of the companion object and into the MainActivity
.
(我通过查看 https://github.com/ligee/kotlin-找到了答案ndk-samples )
这篇关于Android:如何从Kotlin调用ndk函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!