What's the difference between Pinned and StableRef...
# kotlin-native
n
What's the difference between Pinned and StableRef? They look so similar besides maybe one being a data class and another a value class. Wouldn't one of them be enough?
d
Well, the former allows access to data and the latter is just an opaque reference.
n
What do you mean exactly? I can see both StableRef.get and Pinned.get, returning an instance of the pinned type T
d
Accessible from C.
n
If you look at source code they seem to do exactly the same thing, a stable opaque pointer. I can see slight differences in the api (Pinned offers refTo / addressOf for arrays, maybe this is what you are referring to?), but I don't think this justifies having two separate concepts? I am probably missing something
One interesting difference is that StableRef is in "main" folder here https://github.com/JetBrains/kotlin/tree/master/kotlin-native/Interop/Runtime/src , and Pinned is in "native" only. Maybe we have both for historical reasons
d
StableRef is useful for callbacks in C, especially the ones that let you pass "user data" , this lets you reference kotlin objects from staticCFunctions. Pinning just lets you pass a pointer to the underlying array to some C function like fread.
👍 1
n
Yeah I get it. But it's the same concept, if Pinned constructor was public, you could do both things with pinned
Anyway, I now wrapped my head around both so I can live with this 😄 it was confusing though, if there's no reason to, I think that a single concept would be better for beginners.
j
was this the intent of `pin`ned? is there a more succint solution? i am just feeling along to satisfy intellij for the most part until the generics somehow line up.
Copy code
var	buffer= ByteArray(128)
var	iov:iovec =alloc {
	iov_base = buffer.pin().objcPtr().toLong().toCPointer<COpaque>()  as COpaquePointer /* = kotlinx.cinterop.CPointer<out kotlinx.cinterop.CPointed> */
	 iov_len = 128.toULong()
}
toLong() feels like some kind of code smell but i haven't really seen a good breakdown of the C[Opaque]{Value[s]|Pointe{r|d}|Array}{Ref|[Var[Of]]} recipes so far.