ios - 为什么 NSMutableData 改变指针的地址?

标签 ios swift unsafe-pointers

<分区>

我想快速预分配内存并将其包装在 NSMutableData 中,但可以通过指针访问。 所以我有这个:

var vertex = UnsafeMutablePointer<Float>.alloc(numberOfVertex * 3)
vertex.initialize(0)
vertexData = NSMutableData(bytesNoCopy: vertex, length: numberOfVertex * 3 * sizeof(Float))

但是当我检查 vertex 指针的地址时,我看到了与 vertexData.bytes 不同的值,因此据我所知,我不能再使用指针按索引更改数据。 如何避免这种情况并且只有一个内存块?

最佳答案

根据文档,您实际上不能以这种方式使用带有 no-copy 标志的 NSMutableData:

NSMutableData responds to these methods, too, but the bytes are copied anyway and the buffer is freed immediately.

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/BinaryData/Tasks/WorkingBinaryData.html#//apple_ref/doc/uid/20000717-149014

关于ios - 为什么 NSMutableData 改变指针的地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32574034/

相关文章:

释放自定义对象时出现 Iphone SIGBUS 错误

ios - 重新创建谷歌收件箱的 ios 加号按钮

swift - 如何在 Swift 3 中将 UnsafePointer<[Float]> 或 Float Array 数据转换为 Unsafe[Mutable]Pointer<Float>?

null - Swift:gettimeofday 和不安全指针

c++ - 具有未初始化指针的类是否具有未定义的行为?

ios - 如何使用 swift 获取 iOS 构建版本?前 : iOS 11. 3 (15E216)

iphone - 如何解决 -[__NSCFString JSONValue] : unrecognized selector sent to instance when application terminates?

ios - UIView组件已加载但未显示

ios - 如何在 Swift 3 中显示当前位置图标?

ios - 创建日历时中断错误