Generating C# structure from C structure

2019-07-19 18:03发布

问题:

I have several dozens of C structures and I need to use them in C#. A typical C structure looks like this one:

typedef struct _UM_EVENT
{
   ULONG32 Id;
   ULONG32 Orgin;          
   ULONG32 OperationType;  
   ULONG32 Size;           
   LARGE_INTEGER Time;     
   HANDLE ProcessId;
   HANDLE ThreadId;
} UM_EVENT, *PUM_EVENT;

To use this structure in C# I declare it in C# and then do the marshalling stuff, which can be done roughly in this way:

public struct UM_EVENT
{
   public UInt32 Id;             
   public UInt32 Orgin;          
   public UInt32 OperationType;  
   public UInt32 Size;           
   public UInt64 Time;           
   public IntPtr ProcessId;      
   public IntPtr ThreadId;       
}

private void Load(IntPtr event) {

   unsafe
   {
       UM_EVENT header = *(UM_EVENT*)event;
   }
}

IMHO, this approach has the following disadvantages if the code is written a lot of times:

  1. The coding is not fast and does not require much thinking
  2. The code will likely contain many bugs that can remain undetected for long time
  3. The code is not very maintainable, because a change in a C structure requires the same change in the C# structure

So, does anybody know a util that would generate the presented C# code from given C structures automatically? Or is there a completely different way how to comfortably use a large number of C structures in C#?