I need to call C functions that take 2d arrays. The future arrays are created in Swift, and are generally [String]
, but I'm interested in the [[T]]
case too.
The API I'm calling specifies that its functions always copy data passed to them if necessary, so I don't want create a copy of the contents myself just to pass it in, and I only need to worry about the pointers being valid until I can pass them into the C functions. My current approach is to do
let addressArray = someArray.map { (array) in
array.withUnsafeBufferPointer({ (buffer) in
// get an array of addresses to each individual member
return buffer.baseAddress
})
}
addressArray.withUnsafeBufferPointer { bufferPointer in
someCFunction(bufferPointer.baseAddress)
// do something with someArray to attempt to ensure that the pointers are valid past the lifetime of the withUnsafeBufferPointer call
}
This works, but as the pointers returned from withUnsafeBufferPointer
are said to only be valid in that scope, it's clearly wrong (though by being certain to always require that someArray
remain alive until after I'm done with someCFunction
I feel fairly confident that it won't break in the short term). But there must be a better way; what is it?