0

我有一个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($0)) }
print(str)
// Outputs an empty string

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

1 回答 1

0

你似乎不愿意展示你的代码,所以我真的无能为力。但这看起来是错误的:

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

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

换句话说,C char(你的问题的标题)不是 Swift Character - 它们彼此完全不同。AC char 是一个小数字,Swift Character 是面向对象语言中的一个对象,C 对此一无所知!

于 2015-10-19T01:58:47.343 回答