Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best conversion from String into UnsafePointer<Int8>?

To convert String into UnsafePointer I use this:

var tail = ("" as NSString).utf8String

But is there any way to convert without NSString casting?

I use UnsafePointer inside C-library methods.

like image 399
Vyacheslav Avatar asked Mar 04 '23 20:03

Vyacheslav


1 Answers

There's special method exactly for this: .withCString(_:):

yourString.withCString { pointer in
    // work with the pointer
    return result
}

Or if you want it as property there's .utf8CString:

var tail = "".utf8CString // ContiguousArray<CChar> (aka ContiguousArray<Int8>)
// and then
tail.withUnsafeBufferPointer { pointer in
    // work with the pointer
    return result
}
like image 63
user28434'mstep Avatar answered May 16 '23 08:05

user28434'mstep