How to copy a c array to a kotlin array

I’m attempting to copy a *uchar array thats passed in to a kotlin native function from an application written in golang. The array is being allocated in C memory is passed into the following function:

fun doSomething(buffer: CArrayPointer<UByteVar>, bufferSize: Int) {
    val buf = buffer.reinterpret<UByteVar>()
    val bufferCopy = UByteArray(bufferSize)

    for (i in 0.until(bufferSize)) {
        bufferCopy[i] = buf[i]

    // do some other things

As I haven’t been able to find a way to cast the C array to a native kotlin UByteArray, i’m unable to copy this using the builtin array copy method. Normally in C, it would be possible to memcpy straight from one address to another, however, I was unable to find any documentation on how to do this in kotlin.

The above approach works, however, it causes a panic 1 in every 10-20 or so times given the exactly the same input.

Is there a better way to handle copying from a C array to a kotlin array?

Hello, @radix! First of all, I have to say this approach seems to be correct. The only thing I’m missing here is why would one need to instantiate that val buf instead of using buffer from the input parameter. Also, am I understanding correctly that bufferSize and ciphertextSize values are equal?
If you can share an example project reproducing the error, it would help a lot. Probably, it might be a bug here.

Hi @Artyom.Degtyarev, thanks for the reply!

You are correct in that the buf value was not necessary. Having removed that I still see the same issue.

In the example, ciphertextSize and bufferSize are the same, that was a typo from me copying across to a simplified example. I’ve corrected that in my previous post.

I will try and put together a simplified project that demonstrates the issue.

1 Like