https://kotlinlang.org logo
Title
k

Krystian

01/18/2023, 9:32 PM
Would anyone be able to explain to me when and what for would you use reinterpret function? The lack of documentations on it makes it slightly hard to grasp
l

Landry Norris

01/18/2023, 10:39 PM
In C, it's often common to define a few structs that have the same layout at the start. You can cast the pointer in C for this. Kotlin doesn't let you cast the type of a CPointer, so you can reinterpret
It also helps if you want to, for example, reinterpret a pointer. Let's say a library returns an int array, but you want the bytes to send to a file. You can reinterpret the int pointer as a byte pointer to send to the file stream, since that's what you need. Note that this won't cast the contents and it doesn't check validity, so this is unsafe.
n

napperley

01/19/2023, 1:21 AM
In a nutshell the primary use case for using
reinterpret
is casting from one
CPointer
type to another, especially when dealing with C callbacks, and user data that is passed to the callback. Many C libraries use
COpaquePointer
as the type for user data which is equivalent to Kotlin's
Any
data type.
j

Jeff Lockhart

01/19/2023, 1:21 AM
Sometimes an API may appear in Kotlin as a
COpaquePointer
type and
reinterpret()
can be used to massage the type to the correct known type, like
reinterpret<ByteVar>()
.
Haha, what Nick just said.
k

Krystian

01/19/2023, 6:52 AM
Ah perfect thank you for the explanation, that gave me an idea what to do for a test and it worked perfectly well.
l

Landry Norris

01/19/2023, 7:11 PM
To give an example I’m dealing with right now about reinterpret: Java’s JNI can take in jvalue, jobject, or jstring. To make things easier, all 3 have the same memory layout, and the JVM just interprets it as needed. Kotlin’s cinterop sees them as 3 separate types. Because they have the same memory layout, I can just pass whichever in from C, but Kotlin won’t let me pass in jstring when the declared type was jvalue. I can get a ptr to my jstring, reinterpret it as a pointer to a jvalue, and pass in jvaluePtr.pointed.