我正在寻找在Swift中实现合理C互操作性的最简单方法,我当前的块正在将UnsafePointer<Int8>
(const char *
)转换为[Int8]
数组
目前,我有一个天真的算法,可以采用UnsafePointer
和多个字节,并逐个元素地将其转换为数组:
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])
}
}
使用arr.reserveCapacity(length)
可以加快循环本身,但这并不能消除循环本身的问题。
我知道this SO question涵盖了如何将UnsafePointer<Int8>
转换为String
,但String
完全与[T]
完全不同。是否有一种方便的Swift方法将长度字节从UnsafePointer<T>
复制到[T]
?我更喜欢纯粹的Swift方法,而不是通过NSData
或类似方法。如果上述算法真的是唯一的方法,我很乐意坚持下去。
答案 0 :(得分:41)
您可以简单地从Array
UnsafeBufferPointer
func convert(length: Int, data: UnsafePointer<Int8>) -> [Int8] {
let buffer = UnsafeBufferPointer(start: data, count: length);
return Array(buffer)
}
这将创建所需大小的数组并复制数据。
或作为通用功能:
func convert<T>(count: Int, data: UnsafePointer<T>) -> [T] {
let buffer = UnsafeBufferPointer(start: data, count: count);
return Array(buffer)
}
其中length
是指针指向的项的数量。
如果你有一个UInt8
指针但想要从中创建一个[T]
数组
指向数据,那么这是一个可能的解决方案:
// Swift 2:
func convert<T>(length: Int, data: UnsafePointer<UInt8>, _: T.Type) -> [T] {
let buffer = UnsafeBufferPointer<T>(start: UnsafePointer(data), count: length/strideof(T));
return Array(buffer)
}
// Swift 3:
func convert<T>(length: Int, data: UnsafePointer<UInt8>, _: T.Type) -> [T] {
let numItems = length/MemoryLayout<T>.stride
let buffer = data.withMemoryRebound(to: T.self, capacity: numItems) {
UnsafeBufferPointer(start: $0, count: numItems)
}
return Array(buffer)
}
其中length
现在是 bytes 的数量。例如:
let arr = convert(12, data: ptr, Float.self)
将从Float
指向的12个字节创建一个3 ptr
的数组。
答案 1 :(得分:1)
extension NSData {
public func convertToBytes() -> [UInt8] {
let count = self.length / sizeof(UInt8)
var bytesArray = [UInt8](count: count, repeatedValue: 0)
self.getBytes(&bytesArray, length:count * sizeof(UInt8))
return bytesArray
}
}
您可以将行数据转换为byts(Uint8)
复制扩展程序并使用它..
答案 2 :(得分:0)
您也可以使用数组初始化函数:
init(unsafeUninitializedCapacity: Int, initializingWith initializer: (inout UnsafeMutableBufferPointer<Element>, inout Int) throws -> Void) rethrows
如果需要,首先将 unsafeRawPointer 转换为 unsafePointer 然后将指针转换为缓冲区指针,最后将缓冲区指针转换为数组。
示例,假设您有一个 unsafeRawPointer (dataPtr
) 及其大小 (dataSize
)
let numberOfItems = dataSize / MemoryLayout<MyClass>.stride
let myArray = dataPtr.withMemoryRebound(to: MyClass.self,
capacity: numberOfItems) { typedPtr in
// Convert pointer to buffer pointer to access buffer via indices
let bufferPointer = UnsafeBufferPointer(start: typedPtr, count: numberOfItems)
// Construct array
return [MyClass](unsafeUninitializedCapacity: numberOfItems) { arrayBuffer, count in
count = numberOfItems
for i in 0..<count {
arrayBuffer[i] = bufferPointer[i]
}
}
}