Convert a Swift Array of String to a to a C string array pointer

前端 未结 2 988
走了就别回头了
走了就别回头了 2020-12-04 01:42

I\'m on Swift 3, and I need to interact with an C API, which accepts a NULL-terminated list of strings, for example

con         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-04 02:22

    You can proceed similarly as in How to pass an array of Swift strings to a C function taking a char ** parameter. It is a bit different because of the different const-ness of the argument array, and because there is a terminating nil (which must not be passed to strdup()).

    This is how it should work:

    let array: [String?] = ["name1", "name2", nil]
    
    // Create [UnsafePointer]:
    var cargs = array.map { $0.flatMap { UnsafePointer(strdup($0)) } }
    // Call C function:
    let result = command(&cargs)
    // Free the duplicated strings:
    for ptr in cargs { free(UnsafeMutablePointer(mutating: ptr)) }
    

提交回复
热议问题