gpt4 book ai didi

swift - 在 Swift 3 中将 C 数组 ptr 转换为 native 数组

转载 作者:可可西里 更新时间:2023-11-01 00:36:13 26 4
gpt4 key购买 nike

我有一个来自 C 库的指向 float 数组的指针。它的类型是 UnsafeMutablePointer。如何在 Swift 3 中由此创建原生 [Float] 数组?

这是我正在尝试的:

var reconstructedFloats = [Float](repeatElement(0, count: size))
reconstructedFloats.withUnsafeMutableBufferPointer {
let reconstructedFloatsPtr = $0
print(type(of:$0)) // "UnsafeMutableBufferPointer<Float>"
cFloatArrayPtr?.withMemoryRebound(to: [Float].self, capacity: size) {
UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: $0.pointee, as: Float.self)
}

UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: (cFloatArrayPtr?.pointee)!, as: Float.self)
}

这看起来过于复杂,所以希望有一个简单的方法,但即使是这段代码也会产生编译错误:Type of expression is ambiguous without more context

如果您想将其插入 Playground ,这里有一个设计 cFloatArrayPtr 的完整示例:

// Let's contrive a C array ptr:
var size = 3
var someFloats: [Float] = [0.1, 0.2, 0.3]
var cFloatArrayPtr: UnsafeMutablePointer<Float>?

someFloats.withUnsafeMutableBufferPointer {
cFloatArrayPtr = $0.baseAddress
}

print(type(of:cFloatArrayPtr!)) // "UnsafeMutablePointer<Float>"

var reconstructedFloats = [Float](repeatElement(0, count: size))
reconstructedFloats.withUnsafeMutableBufferPointer {
let reconstructedFloatsPtr = $0
print(type(of:$0))
cFloatArrayPtr?.withMemoryRebound(to: [Float].self, capacity: size) {
UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: $0.pointee, as: Float.self)
}

UnsafeMutableRawPointer(reconstructedFloatsPtr.baseAddress!).storeBytes(of: (cFloatArrayPtr?.pointee)!, as: Float.self)
}

print(reconstructedFloats)

最佳答案

您可以从您的指针创建一个UnsafeBufferPointerUnsafeBufferPointer 是一个Sequence,因此您可以直接从中创建一个数组:

let buffer = UnsafeBufferPointer(start: cFloatArrayPtr, count: size)
var reconstructedFloats = Array(buffer)

当然,这会创建一个副本。

关于swift - 在 Swift 3 中将 C 数组 ptr 转换为 native 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39666832/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com