c# - Using the `fixed` keyword with `IntPtr.ToPointer` -


i writing image processing methods , have confusion fixed pointers in unsafe context. fix pointers using fixed keyword in conjunction addressof operator &.

fixed (int* p = &pt.x) // common example not seem apply in case. 

when using bitmap.lockbits, given intptr returned bitmapdata.scan0.

using (var bitmap = new bitmap(800, 600)) {     var data = bitmap.lockbits(new rectangle(0, 0, image.width, image.height), imagelockmode.readonly, pixelformat.format32bppargb);      // error: cannot use fixed statement take address of fixed expression.     fixed (void* p = data.scan0.topointer()) {...}      // works fine [byte* p] remain fixed?     byte* p = (byte*) data.scan0.topointer();      bitmap.unlockbits(data); } 

the question is, need use fixed keyword in context? if not, how byte* p not affected gc?

you don't need fixed here. fortunate, since compiler's not going let use anyway. :)

the call lockbits() method pins memory block. that's what's meant in documentation when says method:

locks bitmap system memory

calling unlockbits() unpins later (which why should put call in finally block).


Comments