19

C サイズの配列を使用していた関数を迅速に操作するにはどうすればよいですか?

Interacting with C APISを読みましたが、まだこれを理解できません。

状態の coords パラメーターのドキュメントfunc getCoordinates(_ coords:UnsafeMutablePointer<CLLocationCoordinate2D>,range range: NSRange):

私はいくつかのことを試しましたが、最近では:

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

次のようなものを使用する必要がありますか?

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

ここで髪を引っ張ります... 何か考えはありますか?

4

2 に答える 2

50

通常、必要なタイプの配列を in-out パラメータとして渡すことができます。別名

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

しかし、そのドキュメントはそれを悪い考えのように思わせます! 幸いなことにUnsafeMutablePointer、静的alloc(num: Int)メソッドが提供されているため、次のように呼び出すことができますgetCoordinates()

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

可変ポインターから実際のCLLocationCoordinate2Dオブジェクトを取得するには、ループするだけで済みます。

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

メモリ リークが発生しないようにするには、次のようにします。

coordsPointer.dealloc(polyline.pointCount)

Arrayインスタンスメソッドがあることを思い出したreserveCapacity()ので、これのより単純な(そしておそらくより安全な)バージョンは次のようになります。

var coords: [CLLocationCoordinate2D] = []
coords.reserveCapacity(polyline.pointCount)
polyline.getCoordinates(&coords, range: NSMakeRange(0, polyline.pointCount))
于 2014-08-29T03:03:04.013 に答える