Is it possible to get a reference to a lambda as a...
# kotlin-native
j
Is it possible to get a reference to a lambda as a C pointer (
CValuesRef<*>
)? My API requires passing an arbitrary Kotlin lambda to a C library as a C function pointer. My understanding is that
staticCFunction()
would not be able to capture the lambda to call inside it:
staticCFunction { ~lambda()~ }
. I am able to have a context passed to the C Function as a
COpaquePointer
though. I could have the lambda passed as this context parameter, if there would be a way to get a reference to it as a C pointer.
j
Thanks. This is along the lines I was considering if a pointer is not possible. The difference is that it's possible for the function to be called more than once (adding multiple listeners), so I'd need to store the lambda reference in a list or array. I could use the context parameter to pass the index into this list of lambdas though. There's also another API requirement where the function can be called multiple times and the lambda is not guaranteed to be called (it's only called under certain conditions and only once in that case). This would be more difficult to handle because I don't want to retain a reference to these lambdas in a list indefinitely.
@msink I finally got my code to a place where I can compile and test and I'm running into this error:
Copy code
e: kotlinx.cinterop.staticCFunction must take an unbound, non-capturing function or lambda, but captures at: <this>
How is it you're avoiding this error? It would seem like you'd experience the same issue capturing
this
for
action
.
Or wait, is it that you're passing the
this
reference with
ref.asCPointer()
, and that's what
with(<http://ref.to|ref.to><Button>())
then resolves back to the kotlin instance?
Ok, after actually checking out your code to look at this closer, it looks like
StableRef
is exactly what I need to get the C pointer reference I need.