Question

I'm having a problem with copying an array of structures as a byte array. The structures are simple RGB structs.

public struct RGBColor { byte r; byte g; byte b; }

Then I have an array of RGBColor[] that represents a scanline that I want to copy to a Bitmap after I've called LockBits(). It will only allow an array of byte[] to be copied using Marshal.Copy().

If I understand correctly (keep in mind I DO NOT UNDERSTAND), I need to marshal the RGBColor[] array to a byte array, copy the data to that new byte[] array, and then copy that array to the bitmap. It seems like there's an unnecessary copying operation occuring and I have an intermediate byte[] array just serving as a middle man.

Isn't there any way I can cast RGBColor[] to byte[] so I can just copy it directly to the locked bitmap?

Was it helpful?

Solution

Marshal.Copy() isn't the right method in this case, it forces you to cough up the byte[] and that hurts in more than one way. What you really need is a method that copies from an IntPtr to an IntPtr so that simply pinning the array gets the job done, avoiding the copy and the structure layout hassle. The .NET framework doesn't have one.

But Windows does, you can pinvoke the memcpy() function. You can tinker the declaration to make it accept your RGBColor[] array. Like this:

  [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
  private static extern int memcpy(IntPtr dest, RGBColor[] srce, int bytes);

The first argument is slightly tricky. You'll need:

  BitmapData bd = ...
  IntPtr dest = new IntPtr((long)bd.Scan0 + scanline * bd.Stride);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top