IOS: convert UnsafeMutablePointer <Int8> to string in 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 wrong, by specifying an invalid string value.

+4
source share
3 answers

If the pointer points to an N-terminal string C from 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)
+16
source

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

If you want utf-8 to be checked:

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

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

let str: String = String(cString: c_str)

, c_str UnsafePointer<UInt8> UnsafePointer<CChar>, C.

+5

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

doesn't seem to work with UnsafeMutablePointer <UInt8> (this is what appears to be in my data).

This I am trivially figuring out how to do something like a C / Perl system function:

let task = Process()
task.launchPath = "/bin/ls"
task.arguments = ["-lh"]

let pipe = Pipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
var unsafePointer = UnsafeMutablePointer<Int8>.allocate(capacity: data.count)
data.copyBytes(to: unsafePointer, count: data.count)

let output : String = String(cString: unsafePointer)
print(output)
//let output : String? = String(validatingUTF8: unsafePointer)
//print(output!)

if I switch to validatingUTF8 (with optional) instead of cString, I get this error:

./ls.swift:19:37: error: cannot convert value of type 'UnsafeMutablePointer<UInt8>' to expected argument type 'UnsafePointer<CChar>' (aka 'UnsafePointer<Int8>')
let output : String? = String(validatingUTF8: unsafePointer)
                                    ^~~~~~~~~~~~~

Thoughts on how to check out UTF8 on channel output (so that I don't get a Unicode error character anywhere)?

(yes, I am not doing a proper check of my optional print (), which is not the problem that I am solving now ;-)).

0
source

Source: https://habr.com/ru/post/1617842/


All Articles