[英]Swift get data from UnsafeMutablePointer<Int8>
我有一个如下的objc函数
-(char *)decrypt:(char *)crypt el:(int)el{}
当我迅速调用此函数时,它返回UnsafeMutablePointer<Int8>
。 现在,我需要从该指针获取数据。 输出应该是这样的字符串
“ 5c9f2cb88787fff26ca8a57982604460201805111017510011111111”
我尝试下面的代码来检索值
String(validatingUTF8: pointer)
但是它返回nil。 如何从此UnsafeMutablePointer<Int8>?
获取值UnsafeMutablePointer<Int8>?
最好的猜测是该数据不是有效的UTF-8字符串。
如果解密失败,则结果很可能是无效的UTF-8,但这只是诊断。
查看十六进制表示形式并确认其有效或使用String(validatingUTF8: pointer)
,其中非UTF-8值将显示为Unicode错误符号:。
我将在这里走出去,假设您的char *
实际上并不指向UTF-8数据,而是指向您希望获取其十六进制表示形式的原始二进制数据。 您可以通过以下方式实现:
// You'll need to know the length of the data. If it's null-terminated,
// read through the pointer until you hit a zero byte; otherwise, use whatever
// facility the API you're using provides to get the data length.
let buffer = UnsafeBufferPointer(start: $0, count: __insert_length_here__)
// and so:
let hexString = buffer.reduce(into: "") { $0 += String(format: "%02x", $1) }
print(hexString) // ta da!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.