Fog Creek Software
Discussion Board

Marshaling big C# structs to a C dll

Does anyone know why there's a size limit on the struct you can pass to a C dll as a ref?  Assuming you have a C function that takes a pointer to a BigType, this will throw a MarshalDirectiveException complaining about the struct being too complex or too big.

in C#

public struct BigType
    public int a;
    public int b;
    public int c;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 65536)]
    public int[] d;

public static extern int GetBigType(ref BigType bt);

in C:

typedef struct tagBigType
    int a;
    int b;
    int c;
    int d[65536];
} BigType;

MY_DLL_API int RequestImage(BigType * const bt);

Ryan Phelps
Wednesday, June 2, 2004

I don't know much about interop w/ C, but could it have something to do with the fact that structs in C# were never intended to be "big"? 

The guidelines (in VS.NET help) say that if you have a small, simple set of data, use a struct, but if it's big or complex, use a class.  In fact, they even go as far as to define "small" as 16 bytes to gain a performance edge over reference types.

The reasoning there is primarily concerning memory management, but clearly structs just aren't meant to hold that much data.

Thursday, June 3, 2004

*  Recent Topics

*  Fog Creek Home