Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to call ndk function from Kotlin?

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
}

}

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()
like image 409
Garf1eld Avatar asked Apr 29 '16 07:04

Garf1eld


Video Answer


2 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)

like image 126
Byte Welder Avatar answered Oct 17 '22 11:10

Byte Welder


Kotlin :

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


 load c++ file
 companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }
like image 42
Makvin Avatar answered Oct 17 '22 10:10

Makvin