Roberto Leinardi
12/14/2024, 12:28 PMcallback1 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:
@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?Roberto Leinardi
12/15/2024, 2:16 PMuser_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?Roberto Leinardi
12/15/2024, 2:19 PMYoussef Shoaib [MOD]
12/15/2024, 7:38 PMRoberto Leinardi
12/16/2024, 9:03 AMuser_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?