我如何与swift中用于获取大小的C数组的函数进行交互?
我阅读了与C APIS的交互,但仍然无法弄清楚这一点.
func getCoordinates(_ coords:UnsafeMutablePointer<CLLocationCoordinate2D>,range range: NSRange)状态的coords参数的文档:"在输入时,您必须提供足够大的C数组结构以容纳所需数量的坐标.在输出时,此结构包含请求的坐标数据."
我尝试了几件事,最近一次:
var coordinates: UnsafeMutablePointer<CLLocationCoordinate2D> = nil
polyline.getCoordinates(&coordinates, range: NSMakeRange(0, polyline.pointCount))
Run Code Online (Sandbox Code Playgroud)
我是否必须使用以下内容:
var coordinates = UnsafeMutablePointer<CLLocationCoordinate2D>(calloc(1, UInt(polyline.pointCount)))
Run Code Online (Sandbox Code Playgroud)
把头发拉出来......有什么想法吗?
Nat*_*ook 49
通常,您可以将所需类型的数组作为输入输出参数传递,也就是说
var coords: [CLLocationCoordinate2D] = []
polyline.getCoordinates(&coords, range: NSMakeRange(0, polyline.pointCount))
Run Code Online (Sandbox Code Playgroud)
但该文档使它看起来像一个坏主意!幸运的是,UnsafeMutablePointer提供了一个静态alloc(num: Int)方法,所以你可以getCoordinates()像这样调用:
var coordsPointer = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(polyline.pointCount)
polyline.getCoordinates(coordsPointer, range: NSMakeRange(0, polyline.pointCount))
Run Code Online (Sandbox Code Playgroud)
要从CLLocationCoordinate2D可变指针中获取实际对象,您应该能够循环遍历:
var coords: [CLLocationCoordinate2D] = []
for i in 0..<polyline.pointCount {
coords.append(coordsPointer[i])
}
Run Code Online (Sandbox Code Playgroud)
因为你不想要内存泄漏,所以完成如下:
coordsPointer.dealloc(polyline.pointCount)
Run Code Online (Sandbox Code Playgroud)
记得Array有一个reserveCapacity()实例方法,因此更简单(也可能更安全)的版本是:
var coords: [CLLocationCoordinate2D] = []
coords.reserveCapacity(polyline.pointCount)
polyline.getCoordinates(&coords, range: NSMakeRange(0, polyline.pointCount))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12016 次 |
| 最近记录: |