C中适当大小的C数组

C中适当大小的C数组

本文介绍了迅速将UnsafeMutablePointer替换为Obj-C中适当大小的C数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何快速与用于获取大小C数组的函数进行交互?

How can I interact with functions in swift that used to take sized C arrays?

我阅读了,但仍然无法解决.

I read through Interacting with C APIS and still can't figure this out.

func getCoordinates(_ coords:UnsafeMutablePointer<CLLocationCoordinate2D>,range range: NSRange)的coords参数的文档指出:在输入时,必须提供一个C结构的数组,该数组足够大以容纳所需的坐标数.在输出时,此结构包含所请求的坐标数据."

The documentation for the coords parameter of func getCoordinates(_ coords:UnsafeMutablePointer<CLLocationCoordinate2D>,range range: NSRange) states: "On input, you must provide a C array of structures large enough to hold the desired number of coordinates. On output, this structure contains the requested coordinate data."

最近我尝试了几件事:

var coordinates: UnsafeMutablePointer<CLLocationCoordinate2D> = nil
polyline.getCoordinates(&coordinates, range: NSMakeRange(0, polyline.pointCount))

我是否必须使用类似的东西:

Would I have to use something like:

var coordinates = UnsafeMutablePointer<CLLocationCoordinate2D>(calloc(1, UInt(polyline.pointCount)))

在这里拉我的头发...有什么想法吗?

Pulling my hair out here... any thoughts?

推荐答案

通常,您可以将所需类型的数组作为输入输出参数(也称为

Normally you can just pass an array of the required type as an in-out parameter, aka

var coords: [CLLocationCoordinate2D] = []
polyline.getCoordinates(&coords, range: NSMakeRange(0, polyline.pointCount))

但是该文档使它似乎是一个坏主意!幸运的是,UnsafeMutablePointer提供了静态的alloc(num: Int)方法,因此您可以像这样调用getCoordinates():

but that documentation makes it seem like a bad idea! Luckily, UnsafeMutablePointer provides a static alloc(num: Int) method, so you can call getCoordinates() like this:

var coordsPointer = UnsafeMutablePointer<CLLocationCoordinate2D>.alloc(polyline.pointCount)
polyline.getCoordinates(coordsPointer, range: NSMakeRange(0, polyline.pointCount))

要从可变指针中获取实际的CLLocationCoordinate2D对象,您应该能够循环遍历:

To get the actual CLLocationCoordinate2D objects out of the mutable pointer, you should be able to just loop through:

var coords: [CLLocationCoordinate2D] = []
for i in 0..<polyline.pointCount {
    coords.append(coordsPointer[i])
}

由于您不希望发生内存泄漏,因此请完成以下操作:

And since you don't want a memory leak, finish up like so:

coordsPointer.dealloc(polyline.pointCount)


请记住,Array有一个reserveCapacity()实例方法,因此它的简单得多(也许更安全)是:


Just remembered Array has a reserveCapacity() instance method, so a much simpler (and probably safer) version of this would be:

var coords: [CLLocationCoordinate2D] = []
coords.reserveCapacity(polyline.pointCount)
polyline.getCoordinates(&coords, range: NSMakeRange(0, polyline.pointCount))

这篇关于迅速将UnsafeMutablePointer替换为Obj-C中适当大小的C数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 19:43