我有一个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