16

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()
Richard Chambers
  • 16,643
  • 4
  • 81
  • 106
Garf1eld
  • 598
  • 3
  • 7
  • 21

2 Answers2

14

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)

ByteWelder
  • 5,464
  • 1
  • 38
  • 45
12
Kotlin :

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


 load c++ file
 companion object {
        init {
            System.loadLibrary("native-lib")
        }
    }
Makvin
  • 3,475
  • 27
  • 26
  • Code only answers arent encouraged as they dont provide much information for future readers please provide some explanation to what you have written – WhatsThePoint Feb 13 '19 at 09:20