Skip to content

Instantly share code, notes, and snippets.

@noahsark769
Created October 16, 2020 19:10
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noahsark769/61cfb7a8b7231e2069a9dab94cf74a62 to your computer and use it in GitHub Desktop.
Save noahsark769/61cfb7a8b7231e2069a9dab94cf74a62 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 = this@toData.size.toULong())
}
public fun NSData.toByteArray(): ByteArray = ByteArray(this@toByteArray.length.toInt()).apply {
usePinned {
memcpy(it.addressOf(0), this@toByteArray.bytes, this@toByteArray.length)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment