在 swift3 中使用字节
Using bytes in swift3
float *vertexBuffer = (float *)positionSource.data.bytes;
'bytes' is unavailable: use withUnsafeBytes instead
但是我不知道怎么用
_ = positionSource?.data.withUnsafeBytes({ (<#UnsafePointer<ContentType>#>) -> ResultType in
})
withUnsafeBytes
是泛型方法,ContentType
是推断
从闭包的类型。有
data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) in
// Use vertexBuffer ...
}
你会得到一个 UnsafePointer<Float>
指向数据中的字节。
请注意,此指针不得在闭包之外使用。
您还可以计算结果并将其从闭包传回
给来电者。示例:
let result = data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) -> Float in
let result = // ... compute result ...
return result
}
我想你可以这样做。
let str = "hello"
let strData = str.data(using: String.Encoding.utf8)!
strData.withUnsafeBytes { (bytes: UnsafePointer<CChar>) -> Void in
print("\(bytes[1])") //exp: access as c string
}
希望能帮到你!
float *vertexBuffer = (float *)positionSource.data.bytes;
'bytes' is unavailable: use withUnsafeBytes instead
但是我不知道怎么用
_ = positionSource?.data.withUnsafeBytes({ (<#UnsafePointer<ContentType>#>) -> ResultType in
})
withUnsafeBytes
是泛型方法,ContentType
是推断
从闭包的类型。有
data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) in
// Use vertexBuffer ...
}
你会得到一个 UnsafePointer<Float>
指向数据中的字节。
请注意,此指针不得在闭包之外使用。
您还可以计算结果并将其从闭包传回 给来电者。示例:
let result = data.withUnsafeBytes { (vertexBuffer: UnsafePointer<Float>) -> Float in
let result = // ... compute result ...
return result
}
我想你可以这样做。
let str = "hello"
let strData = str.data(using: String.Encoding.utf8)!
strData.withUnsafeBytes { (bytes: UnsafePointer<CChar>) -> Void in
print("\(bytes[1])") //exp: access as c string
}
希望能帮到你!