Is it possible to call Kotlin code from a callback...
# kotlin-native
n
Is it possible to call Kotlin code from a callback on the C side (especially in a concurrent environment), and if so what are the key things to watch out for? The cinterop tool has a severe bug ( https://youtrack.jetbrains.com/issue/KT-55030 ) where it doesn't support C structs/unions that contain bit fields. I am trying to work around the issue which is proving to be very difficult to deal with.
i
Is it possible to call Kotlin code from a callback on the C side
Haven't tried it, but I remember reading about it in the docs. Looks like you can convert a Kotlin function to a C pointer and use it as a callback https://kotlinlang.org/docs/native-c-interop.html#callbacks
n
That won't do much good since it is done on the Kotlin side. I am trying to do the inverse if that makes sense.
j
You can use staticCFunction. The lambda can't capture any values though.
Ah, that's what Ignat mentioned. I guess I don't understand your question.
n
With the C side I am talking about C code inside a def file.
j
So you're defining a static function inside the .def file and want to be able to call Kotlin code from there? You might try declaring the Kotlin function's C function signature with
extern
and calling that.
v
You want to have a kotlin function that is passed as a function pointer to a C library so the C library can call it? Then you likely want
staticCFunction
as mentioned by others. Use staticCFunction on the kotlin side and put it into a
val
, and then pass
yourVal.CPointer()
as the "callback" function pointer. The lambda cannot capture values, but typically a C function for configuring a callback will take a
void * data
pointer which will be passed as an argument to the callback. You can use a cinterop
StableRef
to create a pointer to your Kotlin data, and in the staticCFunction lambda, get your kotlin data back.
Hmm, I might have also understood your question wrong. I think what you are looking for is more something like this https://kotlinlang.org/docs/native-dynamic-libraries.html#use-generated-headers-from-c