如何在swift中取消char * const argv []

时间:2015-10-29 01:43:48

标签: swift

我正在尝试制作一个c样式的chars指针数组:

*const argv[] 

我发现我必须使用UnsafePointer<UnsafeMutablePointer<Int8>>

但我不知道如何初始化它。

如何将此普通数组映射到UnsafePointer<UnsafeMutablePointer<Int8>>

let argv = ["/usr/bin/printf", "BBB"]

谢谢

1 个答案:

答案 0 :(得分:2)

简单的方法是让Cocoa为你形成C字符串:

let args = ["/usr/bin/printf","BBB"]
var cs = UnsafeMutablePointer<UnsafeMutablePointer<Int8>>.alloc(2)
for (ix,s) in args.enumerate() {
    cs[ix] = UnsafeMutablePointer<Int8>((s as NSString).UTF8String)
}
var cs2 : UnsafePointer<UnsafeMutablePointer<Int8>> = UnsafePointer(cs)

当心; cs不包含副本。它的指针指向args中的字符串。