views:

362

answers:

1

You have a structure that takes a byte array

byte[]

however, the size of that array depends on the image you are submitting (widthxheight)

So... how do you do

[MarshalAs(UnmanagedType.ByValArray, SizeConst = ???)]
public Byte[] ImageData;

Is the sizeconst a MUST HAVE when working with byte arrays being passed from C# to C dlls?

+1  A: 

You need to change the marshalling type. SizeConst is required if you're marshalling as ByValArray, but not with other types. For details, look at the UnmanagedType enum.

My suspicion is that you want to marshall as a C pointer to the array:

[MarshalAs(UnmanagedType.LPArray)]

This will cause it to marshall through to a standard C array (BYTE*), so only a pointer is passed through. Doing this allows you to pass any sized array. Typically, you'll also want to pass through the array size as another parameter (or image width/height/bpp, which provides the same info), since there's no way in C/C++ to tell that easily.

Reed Copsey
Thanks for the reply Reed. However, I did that and now get this error Invalid managed/unmanaged type combination (Arrays fields must be paired with ByValArray or SafeArray)When building the IntPtr and then Marshal.StructureToPtr... Thoughts?
Olewolfe
Check out the enum. There would be more information required. I was assuming you were marshalling from managed -> unmanaged, but if you're going the other way around, you can either Marhsal it as an IntPtr (instead of a byte[]) or set it up to use a SafeArray.
Reed Copsey
Unfortunately using anything but [MarshalAs(UnmanagedType.ArrayByVal, sizeConst = xxxx)] messes up the memory addressing. So essentially there's a struct (which contains a byte[]) that needs to be converted to an IntPtr so it can be passed to the DLL. And the data in the byte[] is getting messed up. Verified this by copying the data from the IntPtr to a byte[] and looking at the data to find that everything is changed unless I've set the MarshalAs in the struct.
Olewolfe