https://kotlinlang.org logo
#kotlin-native
Title
# kotlin-native
n

napperley

01/03/2023, 12:45 AM
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

Ignat Beresnev

01/03/2023, 1:42 AM
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

napperley

01/03/2023, 1:45 AM
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

Jeff Lockhart

01/03/2023, 3:22 AM
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

napperley

01/03/2023, 4:28 AM
With the C side I am talking about C code inside a def file.
j

Jeff Lockhart

01/03/2023, 4:32 AM
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

vbsteven

01/03/2023, 11:15 AM
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
16 Views