简体   繁体   English

iOS:转换UnsafeMutablePointer <Int8> swift中的字符串?

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

As the title says, what is the correct way to convert UnsafeMutablePointer to String in swift? 正如标题所说,在swift中将UnsafeMutablePointer转换为String的正确方法是什么?

//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. 我尝试使用x.memory.description显然它是错误的,给我一个错误的字符串值。

If the pointer points to a NUL-terminated C string of UTF-8 bytes, you can do this: 如果指针指向以NUL结尾的UTF-8字节的C字符串,则可以执行以下操作:

import Foundation

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

let str = String(cString: x)

Times have changed. 时代变了。 In Swift 3+ you would do it like this: Swift 3+中你会这样做:

If you want the utf-8 to be validated: 如果你想要验证utf-8:

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

If you want utf-8 errors to be converted to the unicode error symbol: 如果要将utf-8错误转换为unicode错误符号:

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. 假设c_str的类型为UnsafePointer<UInt8>UnsafePointer<CChar> ,它与大多数C函数返回的类型相同。

this: 这个:

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

doesn't appear to work with UnsafeMutablePointer<UInt8> (which is what appears to be in my data). 似乎不适用于UnsafeMutablePointer <UInt8>(这似乎是我的数据)。

This is me trivially figuring out how to do something like the C/Perl system function: 这是我简单地弄清楚如何做类似C / Perl系统功能的事情:

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: 如果我切换到validatingUTF8(可选)而不是cString,我收到此错误:

./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 validateUTF8 on the output of the pipe (so I don't get the unicode error symbol anywhere)? 关于如何在管道输出上验证UTF8的想法(所以我没有在任何地方获得unicode错误符号)?

(yes, I'm not doing proper checking of my optional for the print(), that's not the problem I'm currently solving ;-) ). (是的,我没有正确检查我的打印选项(),这不是我正在解决的问题;-))。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM