// 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 { [StructLayout(LayoutKind.Sequential)] struct foo { public int a; public int b; } [DllImport(@"C:\foobar.dll")] static extern void bar1(IntPtr f); [DllImport(@"C:\foobar.dll")] static extern void bar2(IntPtr f, int v); public static void Main(string[] args) { foo f; f.a = 11; f.b = 21; int siz = Marshal.SizeOf(f); IntPtr buf = Marshal.AllocHGlobal(siz); Marshal.StructureToPtr(f, buf, true); Console.WriteLine("values before bar1: " + f.a + " " + f.b); bar1(buf); f = (foo)Marshal.PtrToStructure(buf, typeof(foo)); Console.WriteLine("values after bar1: " + f.a + " " + f.b); Console.WriteLine("values before bar2: " + f.a + " " + f.b); bar2(buf, 1); f = (foo)Marshal.PtrToStructure(buf, typeof(foo)); Console.WriteLine("values after bar2: " + f.a + " " + f.b); Marshal.FreeHGlobal(buf); } } }