How to pass Object array to unmanaged code?
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 incred开发者_开发百科ibly difficult.
Any suggestions or links? Thanx!
What finally worked:
- Passing an array of structs instead of an array of objects (references).
- Putting "[StructLayout(LayoutKind.Sequential, Pack = 1)]" just before the struct definition.
- 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.
- Declaring an array of structs for the argument in the DllImport declaration: "VariableObject[] varObj".
- Declaring a pointer to the class as the parameter on the C++ side. (The C++ class mirrors the C# struct.): "VariableObject* varObj".
Can you cast to a void pointer? Be sure the array of objects is pinned.
In your C#/Managed method signature, mark the input parameter with [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]...
[DllImport(...)]
public void DoTask
(
...,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] int[] results,
...
);
Then call it as you did always. Also, inside the unmanaged code, you can modify this array. I suggest that you send in an extra int telling the unmanaged code what the size of the array is to prevent “array out of bound” modification.
精彩评论