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.
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