hey guys, I'm totally new to kotlin/native, but I ...
# kotlin-native
c
hey guys, I'm totally new to kotlin/native, but I need it for a multiplatform project. Is there any way to convert a ByteArray to a platform.Foundation.NSData?
j
A base 64 encode function I have in my code which also does the conversion:
Copy code
/** Encode [bytes] array into a base64 String */
    actual fun encode(bytes: ByteArray) = memScoped {
        @Suppress("EXPERIMENTAL_API_USAGE")
        NSData.create(
            bytesNoCopy = bytes.toCValues().getPointer(this),
            length = bytes.size.toULong()
        ).base64EncodedStringWithOptions(0) 
    }
And the other way around:
Copy code
/** Decode [base64] string into bytes array */
    actual fun decode(base64: String): ByteArray {
        // For this library end padding is mandatory so add possible missing padding
        val value = base64.padEnd(
            length = ((base64.length+3)/4)*4,
            padChar = '='
        )

        val data = NSData.create(value, 0) ?: throw ParseException("Invalid Base64 value $base64")
        @Suppress("UNCHECKED_CAST")
        val bytePtr = (data.bytes as CPointer<uint8_tVar>)

        @Suppress("EXPERIMENTAL_API_USAGE")
        return ByteArray(data.length.toInt()) { index ->
            bytePtr[index].toByte()
        }
    }
c
ok I just got a similar solution, but I don't know how to build an AutofreeScope to pass to getPointer fun
j
wrap it in memScoped {} block as behind the = sign above
c
thanks!
👍 1
d
Within
memScope
you can just use
.ptr
K 1
c
wow nice usage of scopes here
s
bytes.toCValues().getPointer(this)
Btw, to avoid copying something like this can be used:
Copy code
bytes.usePinned {
    val ptr = it.addressOf(0)
    // remaining code using this pointer.
}