什么是 UnsafeMutablePointer<Void>?如何修改底层内存? [英] What is UnsafeMutablePointer<Void>? How to modify the underlying memory?

查看:23
本文介绍了什么是 UnsafeMutablePointer<Void>?如何修改底层内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to work with SpriteKit's SKMutableTexture class but I don't know how to work with UnsafeMutablePointer< Void >. I have a vague idea that it is a pointer to a succession of byte data in memory. But how can I update it? What would this actually look like in code?

编辑

这是一个可以使用的基本代码示例.我怎样才能让它做一些简单的事情,比如在屏幕上创建一个红色方块?

Here is a basic code sample to work with. How would I get this to do something as simple as create a red square on the screen?

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

        /* ??? */

    }

推荐答案

来自 SKMutableTexture.modifyPixelDataWithBlock 的文档:

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

The texture bytes are assumed to be stored as tightly packed 32 bpp, 8bpc (unsigned integer) RGBA pixel data. The color components you provide should have already been multiplied by the alpha value.

因此,当您获得 void* 时,底层数据是 4x8 位流的形式.

So, while you’re given a void*, the underlying data is in the form of a stream of 4x8 bits.

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

You could manipulate such a structure like so:

// 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&lt;Void&gt;?如何修改底层内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆