Swift and C++ memory question

You're making pointers to the contents of Arrays, and then those arrays immediately get deallocated because they're not referenced anymore. The Array-to-pointer conversion is also only valid for the duration of the call where the Array is passed as an argument…which in this case is the call to UnsafePointer's initializer. (We have an open bug to add a warning for this kind of code.)

There's not a great way to safely build C arrays of pointers to C arrays from a Swift Array-of-Arrays; the best I could come up with involves manually allocating some C arrays and cleaning them up afterwards.

let distances: [UnsafeMutableBuffer<Int64>] = self.distanceResponse.distances.map {
  let buffer = UnsafeMutableBuffer<UInt64>.allocate(capacity: $0.count)
  buffer.initialize(from: $0.lazy.map { Int64($0) })
  return buffer
}
defer {
  distances.forEach { $0.deallocate() }
}
// similar for "durations"
distances.withUnsafeBufferPointer { distancesBuffer in
  durations.withUnsafeBufferPointer { durationsBuffer in
    assert(distancesBuffer.count == durationsBuffer.count)
    var s = RoutingData(
      locationsCount: Int32(distancesBuffer.count),
      distanceMatrix: distancesBuffer.baseAddress
      durationMatrix: durationsBuffer.baseAddress)
    Solve(&s)
  }
}

That's a lot messier, to be sure, but it makes all the lifetimes explicit.