phoganuci
phoganuci

Reputation: 5064

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?

Upvotes: 22

Views: 23962

Answers (6)

Top-Master
Top-Master

Reputation: 8745

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

Upvotes: 0

Swift 5

var cstr = (userStr as NSString).utf8String

Upvotes: 0

Leo
Leo

Reputation: 1585

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.

Upvotes: 8

hnh
hnh

Reputation: 14795

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

Upvotes: 16

Cezary Wojcik
Cezary Wojcik

Reputation: 21845

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

Upvotes: 32

mbeaty
mbeaty

Reputation: 1559

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)

Upvotes: 9

Related Questions