Search code examples
c#.netstructunmanagedmarshalling

Marshal Unmanaged struct to managed code using C#


I need to process the bytes[] when I get from external application. The external application is also done in C# and they send the bytes thru UDP. They are sending the bytes converted from struct which is stated below :

public struct DISPATCH_MESSAGE
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    public char[] federation_name; // Units: nil     Range: nil
}

So, when I get the bytes, I need to take out the char[] inside that, and get the string out of that char[].

I am new to this kind of unmanaged coding.


Solution

  • Probably you should declare it as ByValTStr (depending on the nature of the string, it might be different):

     [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
     public struct DISPATCH_MESSAGE{ 
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]   
        public string federation_name; 
     }
    

    UPDATE: If it's already giving out a char[], it's probably doing the necessary conversion (includes handling encoding) correctly, so I think you'd just need:

    string str = new string(instance.federation_name);