Code:
using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Sequential)]
public struct myS
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
public char[] c;
public UInt32 a;
public UInt32 b;
}
static class NativeInterop
{
public static S MarshalStruct<S>(System.IO.Stream input) where S : struct
{
int size = Marshal.SizeOf(typeof(S)); // size of the managed structure
byte[] buffer = new byte[size]; // byte buffer
input.Read(buffer, 0, size); // read unmanaged struct
GCHandle gch = GCHandle.Alloc(buffer, GCHandleType.Pinned); // allocate a pinned handle to the buffer to prevent the GC from moving it
S ret = (S)Marshal.PtrToStructure(gch.AddrOfPinnedObject(), typeof(S)); // marshal the buffer
gch.Free(); // release the handle
return ret;
}
}
myS s = NativeInterop.MarshalStruct<myS>(new System.IO.FileStream(@"c:\some.file", FileMode.Open, FileAccess.Read));
Add your own error handling as several of those methods can throw exceptions.