更新时间:2023-02-12 16:12:01
C函数
int initialize(int argc, char **argv);
映射为Swift,
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字符串,
如 UnsafePointer< UInt8>中的字符串值所述函数参数行为.
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.