Skip to content

Instantly share code, notes, and snippets.

@indramahkota
Forked from noahsark769/NSDataByteArray.kt
Created May 2, 2025 01:33
Show Gist options
  • Save indramahkota/a7e02870e30bf8b7c1837a984cb4fc13 to your computer and use it in GitHub Desktop.
Save indramahkota/a7e02870e30bf8b7c1837a984cb4fc13 to your computer and use it in GitHub Desktop.
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.allocArrayOf
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import platform.Foundation.NSData
import platform.Foundation.create
import platform.posix.memcpy
public fun ByteArray.toData(): NSData = memScoped {
NSData.create(bytes = allocArrayOf(this@toData),
length = [email protected]())
}
public fun NSData.toByteArray(): ByteArray = ByteArray([email protected]()).apply {
usePinned {
memcpy(it.addressOf(0), [email protected], [email protected])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment