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

前端 未结 4 758
你的背包
你的背包 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:14

    There is also String.withCString() which might be more appropriate, depending on your use case. Sample:

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

    Update Swift 2.2: Swift 2.2 automagically bridges String's to C strings, so the above sample is now a simple:

    var buf = in_addr()
    let s   = "17.172.224.47"
    net_pton(AF_INET, s, &buf)
    

    Much easier ;->

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-10 03:27

    Swift 3 version as @mbeaty's say:

    import Foundation
    
    var str = "Hello World"
    
    var cstr = str.cString(using: String.Encoding.utf8)
    

    Apple API:

    Foundation > String > cString(using:)

    Instance Method

    cString(using:)

    Returns a representation of the String as a C string using a given encoding.

    0 讨论(0)
  • 2020-12-10 03:30

    You can get a CString as follows:

    import Foundation
    
    var str = "Hello, World"
    
    var cstr = str.bridgeToObjectiveC().UTF8String
    

    EDIT: Beta 5 Update - bridgeToObjectiveC() no longer exists (thanks @Sam):

    var cstr = (str as NSString).UTF8String
    
    0 讨论(0)
提交回复
热议问题