James
09/21/2021, 2:56 PMJames
09/21/2021, 3:03 PMfun setInt(pointer: CPointer<IntVar>) {
pointer.pointed.value = 5
}
This can be consumed from C:
libnative_KInt x;
libnative_symbols()->kotlin.root.setInt(&x);
// x == 5
James
09/21/2021, 3:12 PMfun setNullableInt(pointer: CPointer<COpaquePointerVar>) {
pointer.pointed.value = StableRef.create(5).asCPointer()
}
Calling the above from C like so:
libnative_kref_kotlin_Int x;
libnative_symbols()->kotlin.root.setNullableInt(&x);
// Consume x
libnative_symbols()->DisposeStablePointer(x.pinned);
But this results in x being populated with a seemingly random value.napperley
09/21/2021, 8:20 PMnapperley
09/21/2021, 8:27 PMnapperley
09/21/2021, 8:35 PMJames
09/21/2021, 9:54 PMvoid allocate(void* into, void (*allocator)(void*))
This function contains general purpose allocation logic and ultimately delegates the allocation to the provided allocator
function by invoking allocator(into)
. The allocator
function is responsible for instantiating/initializing the value pointed to by into
.
For primitives this works well. Considering the setInt
method above, I could do the following to initialize a KInt from C:
libnative_KInt x;
allocate(&x, libnative_symbols()->kotlin.root.setInt);
// x has successfully been set to 5
However, when dealing with Kotlin objects this becomes much more tricky. For example, consider a nullable KInt which is exposed like so in the C API of my Kotlin library:
typedef struct {
libnative_KNativePtr pinned;
} libnative_kref_kotlin_Int;
I can easily write an allocator
function for this nullable KInt from C by utilizing the builtin createNullableInt
function like so:
void setNullableInt(libnative_kref_kotlin_Int* pointer) {
*pointer = libnative_symbols()->createNullableInt(5);
}
void main() {
// This works fine
libnative_kref_kotlin_Int x;
allocate(&x, setNullableInt);
// x is now a nullable Int with value 5
// Finally, dispose of the object
libnative_symbols()->DisposeStablePointer(x.pinned);
}
But, what I really want is for the setNullableInt
function to be implemented in Kotlin and have a signature identical to the above setNullableInt
function implemented in C.
I suppose my question is:
1. Is it possible to translate the above setNullableInt
from C to Kotlin?
2. And, if so, what does the implementation of such a Kotlin function look like?
Appreciate the help.