Platform Interop - Structures and Arrays
-
Hi! I have following structures: [ StructLayout( LayoutKind.Sequential, CharSet=CharSet.Ansi )] struct ISEG { public short soffset; // segment position (offset) public short slength; // segment length public short segmode; // segment mode } [ StructLayout( LayoutKind.Sequential, CharSet=CharSet.Ansi )] struct IIDX { public short inumseg; // number of segments public IntPtr seg; // (ISEG*) segment information // + some other data } So IIDX structure contains pointer to array of ISEG structures, inumseg defines how many structures there is in array. And I have following DLL function that uses IIDX structure: // short (__cdecl * Open)( pIIDX indexPtr ); [DllImport( "mydll.dll")] private static extern short Open( ref IIDX indexPtr ); In unmanaged C/C++ you would use structure following way: IIDX udtIndex; ISEG udtBseg[2]; udtIndex.inumseg = 2; udtIndex.seg = udtBseg; udtBseg[0].soffset = 1; udtBseg[0].slength = 2; udtBseg[0].segmode = 1; udtBseg[1].soffset = 3; udtBseg[1].slength = 2; udtBseg[1].segmode = 1; Open( &udtIndex ); So, my problem is how I marshal ISEG array pointer to IIDX structure in C#? Should I first allocate memory for two ISEG structures, and then marshal each ISEG structures to right positions in the allocated memory? Or is there easier way to do marshaling (like function or attribute)? Could I use unsafe blocks to get pointer to the array? Any samples? Thank you!