Skip to content

Instantly share code, notes, and snippets.

@indramahkota
Forked from noahsark769/NSDataByteArray.kt
Created May 2, 2025 01:33
Show Gist options
  • Select an option

  • Save indramahkota/a7e02870e30bf8b7c1837a984cb4fc13 to your computer and use it in GitHub Desktop.

Select an option

Save indramahkota/a7e02870e30bf8b7c1837a984cb4fc13 to your computer and use it in GitHub Desktop.

Revisions

  1. @noahsark769 noahsark769 created this gist Oct 16, 2020.
    18 changes: 18 additions & 0 deletions NSDataByteArray.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    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)
    }
    }