How to pass an array of Swift strings to a C function taking a char ** parameter

The C function

int initialize(int argc, char **argv);

is mapped to Swift as

func initialize(argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) -> Int32

This is a possible solution:

let args = ["-c", "1.2.3.4", "-p", "8000"]

// Create [UnsafeMutablePointer<Int8>]:
var cargs = args.map { strdup($0) }
// Call C function:
let result = initialize(Int32(args.count), &cargs)
// Free the duplicated strings:
for ptr in cargs { free(ptr) }

It uses the fact that in strdup($0)
the Swift string $0 is automatically converted to a C string,
as explained in String value to UnsafePointer<UInt8> function parameter behavior.

Leave a Comment