views:

57

answers:

2

I'm trying to pass an array of objects from C# to unmanaged C++, and nothing seems to work.

The compiler won't let me pretend the array is an IntPtr. Casting the array to an IntPtr doesn't work. I've tried to pass the address of pinned data, but this didn't work either.

I just need to pass a pointer to the beginning of the array, and this is turning out to be incredibly difficult.

Any suggestions or links? Thanx!

A: 

Can you cast to a void pointer? Be sure the array of objects is pinned.

Brent Arias
I tried:VariableObject[] varObj = new VariableObject[numVarObjects];GCHandle pinnedData = GCHandle.Alloc(varObj, GCHandleType.Pinned);IntPtr ptr = pinnedData.AddrOfPinnedObject();The Alloc call results in: "Object contains non-primitive or non-blittable data.".
You cannot obtain a pointer to a managed type. An array of managed types is also a managed type, and an object reference is a managed type.
Pavel Minaev
So how can this array be passed to unmanaged code?
A: 

What finally worked:

  1. Passing an array of structs instead of an array of objects (references).
  2. Putting "[StructLayout(LayoutKind.Sequential, Pack = 1)]" just before the struct definition.
  3. Putting "[MarshalAs(UnmanagedType.LPWStr)]" before the string (in the struct definition) to cause the string to appear as a wide-character string on the C++ side.
  4. Declaring an array of structs for the argument in the DllImport declaration: "VariableObject[] varObj".
  5. Declaring a pointer to the class as the parameter on the C++ side. (The C++ class mirrors the C# struct.): "VariableObject* varObj".