Hi, is there a way to wrap `staticCFunction` call?...
# kotlin-native
t
Hi, is there a way to wrap
staticCFunction
call? I'm trying to declare
expect fun <R> staticCFunction(function: () -> R): CPointer<CFunction<() -> R>>
in
commonMain
, but when I try to declare
actual fun <R> staticCFunction(function: () -> R): CPointer<CFunction<() -> R>> = kotlinx.cinterop.staticCFunction(function)
in
iosMain
, I'm getting
kotlinx.cinterop.staticCFunction must take an unbound, non-capturing function or lambda
error. I tried putting in the internal annotations
@VolatileLambda
on
function
and
@TypedIntrinsic(IntrinsicType.INTEROP_STATIC_C_FUNCTION)
on the
actual fun staticCFunction
but it didn't help. Is there anything I could do to make this work?
e
does it work without `expect`/`actual`? the restrictions on
staticCFunction
are strict because it really needs to be static at build time, it can't create a closure there
t
Yeah, sorry I forgot to mention that without
expect/actual
it also doesn't work
I also tried declaring it as
inline fun
so that it'd actually be using
staticCFunction
directly but that also doesn't work
From looking into the compiler sources, it's happening because it gets expression of type
IrGetValueImpl
but expects
IrFunctionReference
or
IrFunctionExpression
. Which sounds like
staticCFunction
has to always be called directly and can't be delegated.
e
I'm not sure what you mean by delegated but it must always be of the form
Copy code
staticCFunction(::function)
where
function
is a static function (e.g. top-level) or equivalent lambda. it may not capture anything because there is a C function pointer cannot hold anything additional
t
By delegated I mean you can't do:
Copy code
inline fun callStaticCFunction(noinline function: () -> Unit) {
  staticCFunction(function)
}
even if you call
callStaticCFunction(::function)
and all the other requirements are met
l
You can't capture anything in the staticCFunction call. In your case, you're capturing the local variable 'function'. In staticCFunction, you can only pass global variables or references to raw methods (not functional variables).
t
Yeah,
function
is global Kotlin function and it works when I call
staticCFunction(::function)
directly, because of how the backend checker is verifying the IR. I don't really capture anything in my
callStaticCFunction
, but it'd require the backend checker to do more extensive check which would probably slow down the compile
a