什么是UnsafeMutablePointer <Void>? 如何修改底层的内存?

我正在尝试与SpriteKit的SKMutableTexture类,但我不知道如何使用UnsafeMutablePointer< Void > 。 我有一个模糊的想法,它是一个指向内存中的字节数据连续的指针。 但是我怎样才能更新呢? 这实际上是什么样的代码?

编辑

这是一个基本的代码示例。 我怎样才能做到这一点,就像在屏幕上创build一个红色方块一样简单?

  let tex = SKMutableTexture(size: CGSize(width: 10, height: 10)) tex.modifyPixelDataWithBlock { (ptr:UnsafeMutablePointer<Void>, n:UInt) -> Void in /* ??? */ } 

SKMutableTexture.modifyPixelDataWithBlock文档:

假设纹理字节被存储为紧密排列的32bpp,8bpc(无符号整数)RGBA像素数据。 您提供的颜色分量应该已经乘以alpha值。

所以,当你被赋予一个void* ,底层数据是以4×8比特stream的forms出现的。

你可以像这样操纵这样的结构:

 // struct of 4 bytes struct RGBA { var r: UInt8 var g: UInt8 var b: UInt8 var a: UInt8 } let tex = SKMutableTexture(size: CGSize(width: 10, height: 10)) tex.modifyPixelDataWithBlock { voidptr, len in // convert the void pointer into a pointer to your struct let rgbaptr = UnsafeMutablePointer<RGBA>(voidptr) // next, create a collection-like structure from that pointer // (this second part isn't necessary but can be nicer to work with) // note the length you supply to create the buffer is the number of // RGBA structs, so you need to convert the supplied length accordingly... let pixels = UnsafeMutableBufferPointer(start: rgbaptr, count: Int(len / sizeof(RGBA)) // now, you can manipulate the pixels buffer like any other mutable collection type for i in indices(pixels) { pixels[i].r = 0x00 pixels[i].g = 0xff pixels[i].b = 0x00 pixels[i].a = 0x20 } } 

UnsafeMutablePointer<Void>是Swift等价于void* – 指向任何东西的指针。 您可以访问底层内存作为其memory属性。 通常情况下,如果你知道底层的types是什么,你将首先强制指向这个types的指针。 然后,您可以使用下标来访问内存中的特定“插槽”。

例如,如果数据真的是一系列的UInt8值,你可以说:

 let buffer = UnsafeMutablePointer<UInt8>(ptr) 

您现在可以访问各个UIInt8值,如buffer[0]buffer[1]等等。