Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

const char *cmd[] = {"name1", "value1", NULL};
command(cmd);

In Swift, the API was imported like

func command(_ args: UnsafeMutablePointer<UnsafePointer<Int8>?>!)

After trying hundreds of times using type casting or unsafeAddress(of:) I still cannot get this work. Even though I pass a valid pointer that passed compilation, it crashes at runtime saying invalid memory access (at strlen function). Or maybe it's something about ARC?

let array = ["name1", "value1", nil]

// ???
// args: UnsafeMutablePointer<UnsafePointer<Int8>?>

command(args)
like image 406
00007chl Avatar asked Jul 08 '16 21:07

00007chl


1 Answers

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<Int8>]:
var cargs = array.map { $0.flatMap { UnsafePointer<Int8>(strdup($0)) } }
// Call C function:
let result = command(&cargs)
// Free the duplicated strings:
for ptr in cargs { free(UnsafeMutablePointer(mutating: ptr)) }
like image 96
Martin R Avatar answered Nov 15 '22 07:11

Martin R