英文:
How do I write to a DIBits structure in Go?
问题
我正在使用一个w32库来实现Go语言的窗口化操作。我不太确定如何处理unsafe.Pointer
,以便能够开始在像素缓冲区中设置像素值。
我使用unsafe.Pointer
,因为w32库希望我在CreateDIBSection函数中传递该指针。
var p unsafe.Pointer
bitmap := w32.CreateDIBSection(srcDC, &bmi, w32.DIB_RGB_COLORS, &p, w32.HANDLE(0), 0)
这段代码成功地给我返回了一个指向存储DIBBits的内存位置的指针。我该如何使用它来写入值呢?
p[idx] = 0xff
这样的代码会报错type unsafe.Pointer does not allow indexing
。我已经阅读了有关unsafe.Pointer
的相关文档,但无法弄清楚如何将其视为一个可以写入的字节缓冲区。
我刚接触Go语言,已经完成了gobyexample.com上的许多示例,但无法解决这个问题。
英文:
I'm using a w32 library to allow me to do Windowing with the Go language. I'm not quite sure what to do with an unsafe.Pointer
that will allow me to start setting pixel values in the pixel buffer.
I use an unsafe.Pointer
, because that's what the w32 library expects me to pass in the CreateDIBSection function.
var p unsafe.Pointer
bitmap := w32.CreateDIBSection( srcDC, &bmi, w32.DIB_RGB_COLORS, &p, w32.HANDLE(0), 0 )
That code succeeds and gives me a pointer to the memory location where the DIBBits are stored. How can I use that to write values?
p[idx] = 0xff
will give me an error type unsafe.Pointer does not allow indexing
. I've read the relevant docs on the unsafe.Pointer, but can't figure out how to treat it as a byte buffer that I can write into.
I'm new to Go and have worked through a lot of the examples at gobyexample.com, but cannot figure this out.
答案1
得分: 1
只需将unsafe.Pointer
强制转换回一个数组(可索引的数组),并以正确的方式进行操作。
尝试了各种转换后,以下是有效的转换方式(假设wid
和hgt
都声明为const
):
pixels := (*[wid*hgt*4]uint8)(ptr)
然后可以使用以下方式进行更改:
pixels[(y*wid+x)*4+0] = 0x00 // 蓝色
pixels[(y*wid+x)*4+1] = 0x00 // 绿色
pixels[(y*wid+x)*4+2] = 0x00 // 红色
英文:
It's just a matter of casting the unsafe.Pointer back to an array (which is indexable) in the proper way.
After trying various casts, this is the one that worked (assuming wid
and hgt
are each declare as const
):
pixels := (*[wid*hgt*4]uint8)(ptr)
then I was able to change them with:
pixels[(y*wid+x)*4+0] = 0x00 // Blue
pixels[(y*wid+x)*4+1] = 0x00 // Green
pixels[(y*wid+x)*4+2] = 0x00 // Red
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论