I'm looking for the simplest ways to achieve reasonable C interoperability in Swift, and my current block is converting an UnsafePointer<Int8>
(which was a const char *
), into an [Int8]
array.
Currently, I have a naïve algorithm that can take an UnsafePointer
and a number of bytes and converts it to an array, element by element:
func convert(length: Int, data: UnsafePointer<Int8>) {
let buffer = UnsafeBufferPointer(start: data, count: length);
var arr: [Int8] = [Int8]()
for (var i = 0; i < length; i++) {
arr.append(buffer[i])
}
}
The loop itself can be sped up by using arr.reserveCapacity(length)
, however that does not remove the issue of the loop itself.
I'm aware of this SO question which covers how to convert UnsafePointer<Int8>
to String
, however String
is a different beast entirely to [T]
. Is there a convenient Swift way of copying length bytes from an UnsafePointer<T>
into a [T]
? I'd prefer pure Swift methods, without passing through NSData
or similar. If the above algorithm is really the only way to do it, I'm happy to stick with that.