Swift - 从 UnsafePointer<UInt8> 转换长度为字符串 [英] Swift - converting from UnsafePointer<UInt8> with length to String
问题描述
我考虑了很多类似的问题,但仍然无法让编译器接受这一点.
I considered a lot of similar questions, but still can't get the compiler to accept this.
Socket Mobile API(在 Objective-C 中)将 ISktScanDecodedData 传递给 Swift 中的委托方法(数据可能是二进制的,我想这就是它不作为字符串提供的原因):
Socket Mobile API (in Objective-C) passes ISktScanDecodedData into a delegate method in Swift (the data may be binary, which I suppose is why it's not provided as string):
func onDecodedData(device: DeviceInfo?, DecodedData d: ISktScanDecodedData?) {
let symbology: String = d!.Name()
let rawData: UnsafePointer<UInt8> = d!.getData()
let rawDataSize: UInt32 = decoded!.getDataSize()
// want a String (UTF8 is OK) or Swifty byte array...
}
在 C# 中,此代码将原始数据转换为字符串:
In C#, this code converts the raw data into a string:
string s = Marshal.PtrToStringAuto(d.GetData(), d.GetDataSize());
在 Swift 中,我可以达到 UnsafeArray
,但后来我卡住了:
In Swift, I can get as far as UnsafeArray
, but then I'm stuck:
let rawArray = UnsafeArray<UInt8>(start: rawData, length: Int(rawDataSize))
或者我看到 String.fromCString
和 NSString.stringWithCharacters
,但它们都不会接受手头的参数类型.例如,如果我可以从 UnsafePointer
转换为 UnsafePointer<()>
,那么这将是可用的(尽管我不确定它是否甚至会注意安全):
Alternatively I see String.fromCString
and NSString.stringWithCharacters
, but neither will accept the types of arguments at hand. If I could convert from UnsafePointer<UInt8>
to UnsafePointer<()>
, for example, then this would be available (though I'm not sure if it would even be safe):
NSData(bytesNoCopy: UnsafePointer<()>, length: Int, freeWhenDone: Bool)
有没有明显的方法可以从这一切中取出一个字符串?
Is there an obvious way to get a string out of all this?
推荐答案
这应该有效:
let data = NSData(bytes: rawData, length: Int(rawDataSize))
let str = String(data: data, encoding: NSUTF8StringEncoding)
Swift 3 更新:
let data = Data(bytes: rawData, count: Int(rawDataSize))
let str = String(data: data, encoding: String.Encoding.utf8)
结果字符串为 nil
如果数据不代表一个有效的 UTF-8 序列.
The resulting string is nil
if the data does not represent
a valid UTF-8 sequence.
这篇关于Swift - 从 UnsafePointer<UInt8> 转换长度为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!