Here are the codes:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode, Pack = 4)]
public class STTEST
{
public DateTime DateTime;
}
static void Main(string[] args)
{
var st0 = new STTEST();
var bs0 = st0.ToBytes();
var st1 = bs0.ToObject<STTEST>();
}
Helper codes:
public static byte[] ToBytes(this object obj)
{
int size = Marshal.SizeOf(obj);
byte[] bytes = new byte[size];
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.StructureToPtr(obj, structPtr, false);
Marshal.Copy(structPtr, bytes, 0, size);
Marshal.FreeHGlobal(structPtr);
return bytes;
}
public static T ToObject<T>(this byte[] bytes)
{
int size = Marshal.SizeOf(typeof(T));
IntPtr structPtr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, structPtr, size);
object obj = Marshal.PtrToStructure(structPtr, typeof(T));
Marshal.FreeHGlobal(structPtr);
return (T)obj;
}
The marshaling operation is right, and the content of bytes is zero. But un-marshaling operation return the st1.DateTime is "1899/12/30". It is supposed to be "0001/01/01"! What's up? :-(