Question:
I'm confused about the lock/unlockBits methods in the Bitmap class. The code snippet below is an example of my messing around with image processing and is something very similar to code i found in msdn library(see link below). Is this managed or unmanaged? It is not marked as unsafe so does that mean it is completely safe? If so, why do people bother using the slow get/set pixel methods when you could just use lock/unlock and do your pixel manipulation where I have put a switch statement?
Also, is there a difference between "managed, unmanaged" and "safe, unsafe", meaning: Is the relationship between the two terms "safe and unsafe" the same as "managed and unmanaged."?
http://msdn2.microsoft.com/en-us/library/5ey6h79d.aspx
// Applies a particular filter. Only accepts 32bppARGB
public void ApplyFilter(Bitmap bmp, Filters filter)
{
// Lock the bitmap's bits.
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
// Get the address of the first line.
IntPtr ptr = bmpData.Scan0;
// Declare an array to hold the bytes of the bitmap.
int bytes = bmpData.Stride * bmp.Height;
byte[] argbValues = new byte[bytes];
// Copy the ARGB values into the array.
System.Runtime.InteropServices.
Marshal.Copy(ptr, argbValues, 0, bytes);
// Apply chosen filter(if any).
switch (filter)
{
case Filters.Invert:
Invert(argbValues);
break;
case Filters.TintRed:
TintRed(argbValues);
break;
}
// Copy the ARGB values back to the bitmap
System.Runtime.InteropServices.
Marshal.Copy(argbValues, 0, ptr, bytes);
// Unlock the bits.
bmp.UnlockBits(bmpData);
}
Answer1:
as far as I know, this is managed code since unsafe part is hidden within the following line:
System.Runtime.InteropServices.Marshal.Copy(ptr, argbValues, 0, bytes);
Answer2:
event though intptr represents a pointer, but it's a struct defined in the .net framework and it's cls compliant.
manage/unmanaged safe/unsafe are not the same.
any code marked as unsafe will not be managed, but not all unmanaged code is unsafe.
The reason being that since the CLR allocates memory and does automatic garbage collection, a pointer could become meaningless as the memory location could change, that's why any unsafe code would be unmanaged.
I am not sure why the intptr struct is safe but it is according to the documentation.
Answer3:
Thank you! You were both very helpful.