如何从 UnsafePointer<CGPoint> - Swift 中提取 UnsafePointer<CGFloat>

How to extract UnsafePointer<CGFloat> from UnsafePointer<CGPoint> - Swift

我正在研究 Swift 中的指针。

例如,此代码以 CGPoint 数组开始,创建一个 UnsafePointer,然后将所有 x 值提取到 CGFloat 数组中:

import Foundation

let points = [CGPoint(x:1.2, y:3.33), CGPoint(x:1.5, y:1.21), CGPoint(x:1.48, y:3.97)]
print(points)

let ptr = UnsafePointer(points)
print(ptr)

func xValues(buffer: UnsafePointer<CGPoint>, count: Int) -> [CGFloat]? {
    return UnsafeBufferPointer(start: buffer, count: count).map { [=13=].x }
}

let x = xValues(buffer: ptr, count: points.count)
print(x)

预期输出为:

[Foundation.CGPoint(x: 1.2, y: 3.33), Foundation.CGPoint(x: 1.5, y: 1.21), Foundation.CGPoint(x: 1.48, y: 3.97)]
0x0000556d6b818aa0
Optional([1.2, 1.5, 1.48])

现在我想直接使用 xValues 函数 return UnsafePointer<CGFloat>,而不是通过 [CGFloat].

我该怎么做,可能吗?

这样输出指针是不安全的。如评论中所述,您应该使用 withUnsafeBufferPointer 方法访问底层缓冲区:

let points = [
  CGPoint(x:1.2, y:3.33), 
  CGPoint(x:1.5, y:1.21), 
  CGPoint(x:1.48, y:3.97)
]

let xValues = points.withUnsafeBufferPointer { buffer in
  return buffer.map { [=10=].x }
}

如果你需要一个指向CGFloat数组的指针,只需使用与上面相同的方法:

xValues.withUnsafeBufferPointer { buffer in 
  // Do things with UnsafeBufferPointer<CGFloat>
}

一个很好的Swift指针教程here


编辑

这是一个工作示例:

let points = [
    CGPoint(x:1.2, y:3.33), 
    CGPoint(x:1.5, y:1.21),
    CGPoint(x:1.48, y:3.97)
]

// Create, init and defer dealoc
let ptr = UnsafeMutablePointer<CGFloat>.allocate(capacity: points.count)
ptr.initialize(repeating: 0.0, count: points.count)
defer {
    ptr.deallocate()
}

// Populate pointer
points.withUnsafeBufferPointer { buffer in
    for i in 0..<buffer.count {
        ptr.advanced(by: i).pointee = buffer[i].x
    }
}

// Do things with UnsafeMutablePointer<CGFloat>, for instance:
let buffer = UnsafeBufferPointer(start: ptr, count: points.count)

for (index, value) in buffer.enumerated() {
    print("index: \(index), value: \(value)")
}