简体   繁体   中英

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

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 string. If I switch this to a compile time defined string the error goes away. Can anyone tell me how to convert a String to a standard c string?

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

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 ;->

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)

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.

斯威夫特 5

var cstr = (userStr as NSString).utf8String

Swift 5

Remember to guarantee the lifetime, like:

let myVariable: String = "some text...";
withExtendedLifetime(myVariable) {
    myVariable.utf8CString.withUnsafeBufferPointer { buffer in
        let result = buffer.baseAddress!;

        // ... Do something with result
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM