我正在尝试将dispatch_queue_create与我在运行时创建的动态String作为第一个参数一起使用。编译器抱怨,因为它需要一个标准的c字符串。如果我将其切换到编译时定义的字符串,则错误消失。谁能告诉我如何将String转换为标准c字符串?
答案 0 :(得分:29)
您可以按如下方式获取CString
:
import Foundation
var str = "Hello, World"
var cstr = str.bridgeToObjectiveC().UTF8String
编辑: Beta 5更新 - bridgeToObjectiveC()
不再存在(感谢@Sam):
var cstr = (str as NSString).UTF8String
答案 1 :(得分:14)
还有String.withCString()可能更合适,具体取决于您的用例。样品:
var buf = in_addr()
let s = "17.172.224.47"
s.withCString { cs in inet_pton(AF_INET, cs, &buf) }
更新Swift 2.2 :Swift 2.2自动将String&C桥接到C字符串,所以上面的示例现在很简单:
var buf = in_addr()
let s = "17.172.224.47"
net_pton(AF_INET, s, &buf)
更容易; - >
答案 2 :(得分:8)
Swift桥接String和NSString。我相信这可能是Cezary回答的替代方案:
import Foundation
var str = "Hello World"
var cstr = str.cStringUsingEncoding(NSUTF8StringEncoding)
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)
答案 3 :(得分:7)
Swift 3版本为@mbeaty's say:
import Foundation
var str = "Hello World"
var cstr = str.cString(using: String.Encoding.utf8)
Apple API:
基金会>字符串> CSTRING(使用:)
实例方法
cString(using:)
使用给定的编码将String的表示形式返回为C字符串。
答案 4 :(得分:0)
斯威夫特 5
var cstr = (userStr as NSString).utf8String