[英]Swift get data from UnsafeMutablePointer<Int8>
I have a objc function like below 我有一个如下的objc函数
-(char *)decrypt:(char *)crypt el:(int)el{}
when I call this function from swift it returns UnsafeMutablePointer<Int8>
. 当我迅速调用此函数时,它返回
UnsafeMutablePointer<Int8>
。 Now I need to get the data from this pointer. 现在,我需要从该指针获取数据。 The output should be a string like this
输出应该是这样的字符串
"5c9f2cb88787fff26ca8a57982604460201805111017510011111111"
“ 5c9f2cb88787fff26ca8a57982604460201805111017510011111111”
I have tried below code to retrieve the value 我尝试下面的代码来检索值
String(validatingUTF8: pointer)
But it returns nil. 但是它返回nil。 How do I get the value from this
UnsafeMutablePointer<Int8>?
如何从此
UnsafeMutablePointer<Int8>?
获取值UnsafeMutablePointer<Int8>?
Best guess is that the data is no a valid UTF-8 string. 最好的猜测是该数据不是有效的UTF-8字符串。
If there decryption failed the result is more than likely invalid UTF-8 but this is just a diagnostic. 如果解密失败,则结果很可能是无效的UTF-8,但这只是诊断。
Look at the hex representation and verify it is valid or use String(validatingUTF8: pointer)
where non UTF-8 values will be displayed as the unicode error symbol: . 查看十六进制表示形式并确认其有效或使用
String(validatingUTF8: pointer)
,其中非UTF-8值将显示为Unicode错误符号:。
I'm going to go out on a limb here and assume that your char *
doesn't actually point to UTF-8 data, but rather to raw binary data of which you are hoping to get a hexadecimal representation. 我将在这里走出去,假设您的
char *
实际上并不指向UTF-8数据,而是指向您希望获取其十六进制表示形式的原始二进制数据。 You can do that via: 您可以通过以下方式实现:
// 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.