// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Runtime.InteropServices; namespace E { public class Program { private static byte[] ConvertStructToBytes(object o) { int siz = Marshal.SizeOf(o); IntPtr buf = Marshal.AllocHGlobal(siz); byte[] res = new byte[siz]; Marshal.StructureToPtr(o, buf, true); Marshal.Copy(buf, res, 0, siz); Marshal.FreeHGlobal(buf); return res; } private static object ConvertBytesToStruct(byte[] b, Type t) { IntPtr buf = Marshal.AllocHGlobal(b.Length); Marshal.Copy(b, 0, buf, b.Length); object res = Marshal.PtrToStructure(buf, t); Marshal.FreeHGlobal(buf); return res; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct Nielle { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 3)] public string str1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 3)] public string str2; } public static void Main(string[] args) { Nielle n = new Nielle(); n.str1 = "1234567"; n.str2 = "abcdefg"; Console.WriteLine(n.str1); Console.WriteLine(n.str2); Nielle n2 = (Nielle)ConvertBytesToStruct(ConvertStructToBytes(n), typeof(Nielle)); Console.WriteLine(n2.str1); Console.WriteLine(n2.str2); } } }