Home » Android » Android: How to call ndk function from Kotlin?

Android: How to call ndk function from Kotlin?

Posted by: admin June 15, 2020 Leave a comment

Questions:

This code works on Java. But after migration to Kotlin, compiler higlits method native fun stringFromNative(): String as error with following text:

Function without a body must be abstract

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
}
}

Thanks @KenVanHoeylandt!

Andswer is:

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
}

}
How to&Answers:

Put external fun stringFromNative(): String outside of the companion object and into the MainActivity.

(I found the answer by looking at https://github.com/ligee/kotlin-ndk-samples)

Answer:

Kotlin :

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


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