将 C 字符数组(不安全指针)转换为字符串

Converting C char array (unsafe pointer) to String

我有一个 UnsafeMutablePointer<Character> 由 CoreFoundation 方法填充。

如果我使用 %s 占位符对它进行 NSLog,它的输出就很好。

但是如果我尝试使用 Swift 的 print 它只会写入内存地址。

几乎尝试了所有...我也不明白为什么如果我尝试访问底层 memory 属性 我会得到 EXC_BAD_ACCESS.

let deviceName = UnsafeMutablePointer<Character>.alloc(64)

/* other statements in which deviceName is filled */

NSLog("device %s by %s", deviceName, manufacturerName)
// Outputs correctly the string

print(String(deviceName[0]))
// Get an EXC_BAD_ACCESS error at runtime

print(String(deviceName.memory))
// Get an EXC_BAD_ACCESS error at runtime

let str = withUnsafePointer(&deviceName) { String.fromCString(UnsafePointer([=10=])) }
print(str)
// Outputs an empty string

print("\(deviceName) by \(manufacturerName)")
// Outputs just memory addresses

你似乎不愿意展示你的代码,所以我真的帮不上忙。但这看起来是错误的:

let deviceName = UnsafeMutablePointer<Character>.alloc(64)
/* other statements in which deviceName is filled */

这不是获取 Swift 中的 C 字符串的方法,如果您认为 Swift 中的 C 字符串,你错了;它需要是一个 Int8 数组(C 字符),而不是 Swift 字符(一个结构!),才能成为一个 C 字符串。

换句话说,C char(你的问题的标题)不是 Swift 字符 - 它们彼此 nothing 一样。 C 字符是一个小数字,Swift 字符是 object-oriented 语言中的 object,C 对此一无所知!