Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Convert UnsafeMutablePointer<Int8> to String in swift?

Tags:

ios

swift

As the title says, what is the correct way to convert UnsafeMutablePointer to String in swift?

//lets say x = UnsafeMutablePointer<Int8> 

var str = x.memory.????

I tried using x.memory.description obviously it is wrong, giving me a wrong string value.

like image 970
user3162662 Avatar asked Nov 28 '15 18:11

user3162662


2 Answers

If the pointer points to a NUL-terminated C string of UTF-8 bytes, you can do this:

import Foundation

let x: UnsafeMutablePointer<Int8> = ...
// or UnsafePointer<Int8>
// or UnsafePointer<UInt8>
// or UnsafeMutablePointer<UInt8>

let str = String(cString: x)
like image 140
rob mayoff Avatar answered Sep 27 '22 19:09

rob mayoff


Times have changed. In Swift 3+ you would do it like this:

If you want the utf-8 to be validated:

let str: String? = String(validatingUTF8: c_str)

If you want utf-8 errors to be converted to the unicode error symbol: �

let str: String = String(cString: c_str)

Assuming c_str is of type UnsafePointer<UInt8> or UnsafePointer<CChar> which is the same type and what most C functions return.

like image 33
LimeRed Avatar answered Sep 27 '22 19:09

LimeRed