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

Bre*_*ret 9 pointers ios sprite-kit swift

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

编辑

这是一个可以使用的基本代码示例.我怎么能做到这一点就像在屏幕上创建一个红色方块一样简单?

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

        /* ??? */

    }
Run Code Online (Sandbox Code Playgroud)

Air*_*ity 12

来自以下文档SKMutableTexture.modifyPixelDataWithBlock:

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

因此,当您获得a时void*,基础数据采用4x8位流的形式.

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

// 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
    }
}
Run Code Online (Sandbox Code Playgroud)


mat*_*att 7

UnsafeMutablePointer<Void>是Swift的等价物void*- 指向任何东西的指针.您可以访问底层内存作为其memory属性.通常,如果您知道底层类型是什么,那么您将首先强制指向该类型的指针.然后,您可以使用下标来访问内存中的特定"插槽".

例如,如果数据实际上是一系列UInt8值,您可以说:

let buffer = UnsafeMutablePointer<UInt8>(ptr)
Run Code Online (Sandbox Code Playgroud)

您现在可以将各个UIInt8值作为buffer[0],buffer[1]等等访问.