如何在Swift语言中将String转换为CString?

ban*_*edo 15 swift

我正在尝试将dispatch_queue_create与我在运行时创建的动态String一起用作第一个参数.编译器抱怨,因为它需要一个标准的c字符串.如果我将其切换到编译时定义的字符串,则错误消失.谁能告诉我如何将String转换为标准c字符串?

Cez*_*cik 30

你可以得到CString如下:

import Foundation

var str = "Hello, World"

var cstr = str.bridgeToObjectiveC().UTF8String
Run Code Online (Sandbox Code Playgroud)

编辑: Beta 5更新 - bridgeToObjectiveC()不再存在(感谢@Sam):

var cstr = (str as NSString).UTF8String
Run Code Online (Sandbox Code Playgroud)

  • bridgeToObjectiveC在beta 5中消失了 - 你现在需要使用`(str as NSString).UTF8String` (5认同)

hnh*_*hnh 14

还有String.withCString()可能更合适,具体取决于您的用例.样品:

var buf = in_addr()
let s   = "17.172.224.47"
s.withCString { cs in inet_pton(AF_INET, cs, &buf) }
Run Code Online (Sandbox Code Playgroud)

更新Swift 2.2:Swift 2.2自动将String's桥接到C字符串,所以上面的示例现在很简单:

var buf = in_addr()
let s   = "17.172.224.47"
net_pton(AF_INET, s, &buf)
Run Code Online (Sandbox Code Playgroud)

更容易; - >


mbe*_*aty 8

Swift桥接String和NSString.我相信这可能是Cezary答案的替代方案:

import Foundation

var str = "Hello World"

var cstr = str.cStringUsingEncoding(NSUTF8StringEncoding)
Run Code Online (Sandbox Code Playgroud)

API文档:

/* Methods to convert NSString to a NULL-terminated cString using the specified
   encoding. Note, these are the "new" cString methods, and are not deprecated 
   like the older cString methods which do not take encoding arguments.
*/
func cStringUsingEncoding(encoding: UInt) -> CString // "Autoreleased"; NULL return if encoding conversion not possible; for performance reasons, lifetime of this should not be considered longer than the lifetime of the receiving string (if the receiver string is freed, this might go invalid then, before the end of the autorelease scope)
Run Code Online (Sandbox Code Playgroud)


Leo*_*Leo 7

Swift 3版本为@ mbeaty的说法:

import Foundation

var str = "Hello World"

var cstr = str.cString(using: String.Encoding.utf8)
Run Code Online (Sandbox Code Playgroud)

Apple API:

Foundation> String> cString(使用:)

实例方法

cString(using:)

使用给定的编码返回String的表示形式作为C字符串.