Can an UnsafeBufferPointer to local scope Array outlive it's own reference?

As an example of how you might do this recursively, I have thrown together a solution to the common problem: "How do I take [String] and turn it into [UnsafePointer<CChar>]?" that uses recursion. Hopefully you'll be able to see how it would translate:

extension Array where Element == String {
    func withArrayOfCStrings<ResultType>(_ block: ([UnsafePointer<CChar>]) throws -> ResultType) rethrows -> ResultType {
        func pointerGenerator(strings: inout ArraySlice<String>, cStrings: inout [UnsafePointer<CChar>], block: ([UnsafePointer<CChar>]) throws -> ResultType) rethrows -> ResultType {
            if let nextString = strings.popFirst() {
                return try nextString.withCString { cString in
                    cStrings.append(cString)
                    return try pointerGenerator(strings: &strings, cStrings: &cStrings, block: block)
                }
            } else {
                return try block(cStrings)
            }
        }

        var stringSlice = self[...]
        var cStrings = Array<UnsafePointer<CChar>>()
        cStrings.reserveCapacity(stringSlice.count)
        return try pointerGenerator(strings: &stringSlice, cStrings: &cStrings, block: block)
    }
}
3 Likes