I’m working with a C library where a native functi...
# kotlin-native
r
I’m working with a C library where a native function accepts two callbacks (
callback1
and
callback2
) that share the same
user_data
parameter. The callbacks have different signatures, but both expect to receive the same
user_data
when invoked. Here’s a simplified Kotlin/Native signature of the native function:
Copy code
@CCall
external fun nativeFunction(
    callback1: CPointer<CFunction<(Int, CPointer<out CPointed>?) -> Unit>>?,
    callback2: CPointer<CFunction<(String, CPointer<out CPointed>?) -> Boolean>>?,
    user_data: CPointer<out CPointed>?
)
My goal is to pass two separate Kotlin lambdas (
lambda1
and
lambda2
) as the callbacks and store them in a single
user_data
. How can I combine these lambdas into a single
user_data
parameter using Kotlin/Native's
StableRef
? Is this even possible with K/N?
Hi everyone, I wanted to provide some additional context and ask if there’s a Kotlin/Native equivalent for a workaround I’ve seen in Java. In Java, there’s a way to handle similar scenarios without using the
user_data
parameter directly. The Java workaround leverages the
Linker
API and
MethodHandles
. Specifically, it creates a native function pointer (
upcallStub
) to a
MethodHandle
bound to an instance method, where the instance itself becomes the first parameter. This eliminates the need for
user_data
because the native code can directly invoke the callback with all necessary parameters. Here’s a quick summary of how it works in Java: 1. Use the
Linker
API’s
upcallStub
method to create a native function pointer. 2. Bind the instance parameter (
this
) to the
MethodHandle
in advance. 3. Pass the resulting native function pointer to the C library, where it serves as the callback. 4. The C library invokes the native callback, and the Java method is called directly with the correct instance and additional parameters. Documentation for
upcallStub
is here My question is: Does Kotlin/Native provide any similar mechanism where callbacks can be handled directly without relying on
user_data
? Or alternatively, is there a way to "combine" multiple lambdas into a single
StableRef
or similar construct that can serve as the shared
user_data
?
an example of how it can be used in Java: https://github.com/jwharm/java-gi/pull/23/files
y
I mean, combining multiple lambdas should be as simple as a data class, no?
r
yeah I guess that could work 😅 since I'm generating bindings from GObject Introspection (GIR) files the Java approach seems also interesting, as I could skip the
user_data
completely (including the detection of shared params and combination of them in custom data classes), do you know if something like this is available in K/N?