How do you convert `ByteArray` to and from `CFData...
# kotlin-native
j
How do you convert
ByteArray
to and from
CFDataRef
? I found this for converting to/from
NSData
, but having a hard time figuring out how to do something similar for
CFDataRef
. I need to create a
SecCertificateRef
, which I’m using
SecCertificateCreateWithData()
and
SecCertificateCopyData()
to create and get the data from.
I came up with this:
Copy code
fun CFDataRef.toByteArray(): ByteArray {
    val length = CFDataGetLength(this)
    return UByteArray(length.toInt()).apply {
        val range = CFRangeMake(0, length)
        CFDataGetBytes(this@toByteArray, range, refTo(0))
    }.toByteArray()
}
Is it required to create a
UByteArray
first or can the
refTo()
of
ByteArray
be safely cast from
CValueRef<ByteVarOf<Byte>>
to the
CValuesRef<UByteVarOf<UByte>>
that
CFDataGetBytes()
requires?
And for the conversion to:
Copy code
fun ByteArray.toCFData(): CFDataRef =
        CFDataCreate(null,
                toUByteArray().refTo(0),
                size.toLong())!!
Same question about the need to convert to
UByteArray
, or if casting the address would work without needing to copy data twice. Am I on the right track with these?
After some testing, these routines seem to work. I just replaced
toUByteArray()
and
toByteArray()
with
asUByteArray()
and
asByteArray()
to avoid the extra copy.
360 Views