Marshaling Complex Structs
So Microsoft has done a great deal to help with interop but sometimes it gets tricky. For instance, last week I was trying to call a C++ function which expected a semi-complex struct as its parameter... typedef struct { int serial_number; struct in_addr ip_address; time_t oldestfile[MAXDRDCHANNELS]; time_t newestfile[MAXDRDCHANNELS]; int group[MAXDRDCHANNELS]; char groupname[MAXDRDCHANNELS][NAMELENGTH]; char commonname[MAXDRDCHANNELS][NAMELENGTH]; } foo; After crunching away for a while, the solution was... private struct Foo { int serialNumber; int ipAddress; int oldestFile0; int oldestFile1; int oldestFile2; int oldestFile3; int newestFile0; int newestFile1; int newestFile2; int newestFile3; int group0; int group1; int group2; int group3; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char groupName0; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char groupName1; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char groupName2; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char groupName3; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char commonName0; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char commonName1; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char commonName2; [MarshalAs(UnmanagedType.ByValArray, ArraySubType=UnmanagedType.U1, SizeConst=21)] char commonName3; } In this case, I knew the array members of the struct were only ever going to contain 4 elements, so I just had to pass them in as individual variables. Things got tricky when I was trying to marshal a C++ char array. You can see by setting the above attribute on the char with an explicit size and type, I got away with it. |
Comments on "Marshaling Complex Structs"