AthanasiusOfAlex AthanasiusOfAlex - 9 months ago 210
Swift Question

Swift 3: convert a null-terminated UnsafePointer<UInt8> to a string

I have a c api that returns a null terminated string that is an array of type

unsigned char*
(which would correspond to

Swift has the initializer
, but the argument has to be
), and there is no trivial way to convert between the two.

How do I convert from this null-terminated c-string to a Swift string?


In Swift 3, String has two initializers

public init(cString: UnsafePointer<CChar>)
public init(cString: UnsafePointer<UInt8>)

therefore it can be created from (null-terminated) sequences of both signed and unsigned characters. So

let s = String(cString: yourCharPointer)

should just work.