using System; using System.Runtime.InteropServices; namespace MarshalDemo { class Program { private static UserData userData; static void Main(string[] args) { userData.myString = "abc"; userData.myInt = 100; int size = Marshal.SizeOf(userData); IntPtr pUserData = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(userData, pUserData, true); UserData userData2 = (UserData)Marshal.PtrToStructure(pUserData, typeof(UserData)); Marshal.FreeHGlobal(pUserData); Console.WriteLine(userData2.myString); Console.WriteLine(userData2.myInt); Console.Read(); } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet = System.Runtime.InteropServices.CharSet.Ansi)] public struct UserData { [System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst = 15)] public string myString; public int myInt; } }