Hello, I have a C function that wants to take in a...
# multiplatform
k
Hello, I have a C function that wants to take in a
CPointer<uint8_tVar>
as input, the wrapper will take in a string value that will need to be converted to this type. I am currently doing the following
Copy code
fun storeGenerateRawKey(key: String): String? {
    var byteArray = key.encodeToByteArray()
    var uIntArray = UIntArray(byteArray.size) { i -> byteArray[i].toUInt()}
    memScoped {
        val buffer = cValue<ByteBuffer>{
           data = uIntArray.refTo(0) as CPointer<uint8_tVar>
           len = uIntArray.size.toLong()
        }
    }

... some more opertations ...

    return some string or null
}
where the byteBuffer is the struct defined in the library that I am importing. My main concern is the type cast and if this is the correct and safe way to do this conversion.
j
You can use reinterpret to cast a native pointer to another type.
k
The result of refTo(0) is a CPointer I am not seeing a way to get a native pointer back from the array. That link is saying to use a plain Kotlin cast for CPointers so I would assume this is correct then?
j
Try
data = uIntArray.refTo(0).getPointer(this@memScoped).reinterpret<uint8_tVar>()
The reference is only guaranteed to be valid within the
memScoped
block though.
k
I’ll take a look at it
I ended up taking the input string and converting it to a cstring using the
.cstr
property and then taking that and making a
uint8_tVar
array with allocArray in my memscope and just coping over each byte to the array with
uIntByteBuffer[i] = cstring.ptr[i].toUByte()
inside a for loop. This resulted in a correctly typed array for what the c struct was expecting. Hopefully that is enough information if someone needs to do this in the future.