Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm dealing with a commercial instrumentation DLL that has a C API, so that code can't be changed. We're using DLLIMPORT to use the API routines in C# code. One function takes a pointer to a complex struct, and this one isn't obvious to me whether we can marshal it.

typedef struct eibuf
{
   unsigned short buftype;
   struct
   {
      unsigned char etype;
      unsigned int edata;
   } error[33];
} EIBUF;

My research indicates that the only fixed arrays allowed in C# structs are those with primitive data, so I haven't been able to construct an equivalent data type.

One way to handle this is to create an interface wrapper in C that will flatten the struct out to an array of integer type, which of course can then easily be marshaled from the C# code.

The wrapper function would just declare an EIBUF variable and set all the fields from the array elements, then call the function from the instrumentation API with that. That's kind of our default plan unless there's something more direct that can be done.

Any thoughts?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

It is possible. Just declare explicit struct type for your error items:

[StructLayout(LayoutKind.Sequential)]
struct ErrorDescriptor
{
      Byte etype;
      Uint32 edata;
}

[StructLayout(LayoutKind.Sequential)]
struct EIBUF
{
   Uint16 buftype;
   [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 33)]
   ErrorDescriptor[] error;
}
share|improve this answer
    
That looks pretty solid. I tried it with a dummy stand-in for the DLL and it seemed to pass the data through. –  user3849884 Aug 6 '14 at 19:21

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.