AthanasiusOfAlex AthanasiusOfAlex - 2 months ago 105
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
UnsafePointer<UInt8>
).

Swift has the initializer
String(validatingUTF8:)
, but the argument has to be
UnsafePointer<CChar>
(a.k.a.
UnsafePointer<Int8>
), 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?

Answer

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.

Comments