且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Swift 字符串数组传递给采用 char ** 参数的 C 函数

更新时间:2023-02-12 16:19:55

C 函数

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

映射到 Swift 为

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) }

它使用了strdup($0)中的事实Swift 字符串 $0 会自动转换为 C 字符串,如 String value to UnsafePointer 中所述函数参数行为.

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.