N/Direct - The .NET Interoperability Resource Center 

FAQ

 

 

 

Most Valuable Professional

When I try to use a structure containing an array of other structures, I get an exception. What's wrong?
Written: 6/23/2002 Updated: 6/23/2002

Even though your source code compiles correctly, the interop marshaler doesn't currently support this. Trying to use such a structure in an interop call will usually result in an ArgumentException or TypeLoadException.

If the array contains few members, the easiest workaround is probably to flatten the array, i.e. create a separate field for each array member. The downside of this approach is of course that you lose the ability to access the member by index.

C#
struct Foo
{
  public int i, j;
}
struct Bar
{
  // This doesn't work
  [MarshalAs(UnmanagedType.ByValArray, SizeConst=4)]
  public Foo[] FooArray;
}
// Change Bar to
struct Bar
{
  public Foo FooArray0, FooArray1, FooArray2, FooArray3;
}
    

VB.NET
Structure Foo
  Public i, j As Integer
End Structure
Structure Bar
  ' This doesn't work
  <MarshalAs(UnmanagedType.ByValArray, SizeConst:=4)> _
  Public FooArray() As Foo
End Structure
' Change Bar to
Structure Bar
  Public FooArray0, FooArray1, FooArray2, FooArray3 As Foo
End Structure
    

If the array has many members, or perhaps even is of variable size, it's probably easier to allocate some unmanaged heap memory and work against that instead. For an example of this, see How do I deal with variable length structures?

See also
How do I deal with variable length structures?