Last active
January 25, 2024 14:59
-
-
Save yandroidUA/ed1e67c90182e6ae83a8408de413c55c to your computer and use it in GitHub Desktop.
NSData to ByteArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @OptIn(ExperimentalForeignApi::class, BetaInteropApi::class) | |
| internal inline fun ByteArray.toData(offset: Int = 0, length: ULong = size.toULong()): NSData { | |
| if (isEmpty()) return NSData() | |
| val pinned = pin() | |
| return NSData.create( | |
| bytesNoCopy = pinned.addressOf(offset), | |
| length = length, | |
| deallocator = { _, _ -> pinned.unpin() } | |
| ) | |
| } | |
| @OptIn(ExperimentalForeignApi::class) | |
| internal inline fun NSData.toByteArray(): ByteArray { | |
| val size = length.toInt() | |
| val byteArray = ByteArray(size) | |
| if (size > 0) { | |
| byteArray.usePinned { pinned -> | |
| memcpy(pinned.addressOf(0), this.bytes, this.length) | |
| } | |
| } | |
| return byteArray | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment