How do you convert a String to a CString in the Swift Language?

前端 未结 4 760
你的背包
你的背包 2020-12-10 02:45

I am trying to use dispatch_queue_create with a dynamic String that I am creating at runtime as the first parameter. The compiler complains because it expects a standard c

4条回答
  •  一生所求
    2020-12-10 03:19

    Swift bridges String and NSString. I believe this may be possible alternative to Cezary's answer:

    import Foundation
    
    var str = "Hello World"
    
    var cstr = str.cStringUsingEncoding(NSUTF8StringEncoding)
    

    The API documentation:

    /* 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)
    

提交回复
热议问题