natario1
10/13/2023, 5:42 PMreinterpret<T>()
-ing a pointer, instead of simple (unchecked) casting? I thought the function performs checks based on the new T
type, but looking at source code, it’s not even inline/reified. I don’t think the runtime receives the type information. So what kind of safety does reinterpret()
provide?
And related, is there any case were unchecked cast is legitimate? Maybe when size/align won’t change?damian
10/13/2023, 7:03 PMinterpretCPointer
which is annotated with TypedIntrinsic
, suggesting that it's implemented as a compiler intrinsic. I don't know the answer to your question thoughephemient
10/13/2023, 8:07 PMas
would normally providenatario1
10/14/2023, 9:22 AMCPointer<A>
to CPointer<B>
would have almost zero cost, it’s even the same type. On the other hand the interpret call creates a new CPointer
instance and has a !!
.Joakim Forslund
10/15/2023, 12:52 PMnatario1
10/15/2023, 3:12 PMas
though, in which case, why is it not implemented as as
under the hood?ephemient
10/15/2023, 4:11 PMval y = x.reinterpret<T>()
doesn't return a new instance, it is like val y = x
except that Kotlin now treats that part of memory as type T
whether that is correct or notnatario1
10/15/2023, 5:20 PMinterpretCPointer
takes this.rawValue
(not this
) and returns a CPointer. Of course there might be compiler/runtime magic under the hoodJoakim Forslund
10/15/2023, 5:31 PMnatario1
10/15/2023, 5:54 PMclass PointerTests {
@Test
fun testInterpretPointer() {
memScoped {
var intPtr: CPointer<IntVar> = alloc<IntVar>().ptr
var longPtr: CPointer<LongVar> = alloc<LongVar>().ptr
measureTime {
repeat(200000) {
longPtr = intPtr.reinterpret()
intPtr = longPtr.reinterpret()
}
}.also {
println("testInterpretPointer: $it")
}
}
}
@Test
fun testCastPointer() {
memScoped {
var intPtr: CPointer<IntVar> = alloc<IntVar>().ptr
var longPtr: CPointer<LongVar> = alloc<LongVar>().ptr
measureTime {
repeat(200000) {
intPtr = longPtr as CPointer<IntVar>
longPtr = intPtr as CPointer<LongVar>
}
}.also {
println("testCastPointer: $it")
}
}
}
}
Edoardo Luppi
10/16/2023, 7:15 PMreinterpret
is unsafeCast
in K/JS?ephemient
10/16/2023, 7:17 PMEdoardo Luppi
10/16/2023, 7:18 PMunsafeCast
is an extension function on Any