// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Runtime.InteropServices; using System.Text; public class TestDN { // structs are defined with explicit layout so they can be serialized/desrialized to/from C stucts [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=4)] public struct MgData1 { public int iv; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=50)] public string sv; } [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=4)] public struct MgData2 { public int iv1; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=50)] public string sv1; public int iv2; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=50)] public string sv2; } // DLL functions are defined, arguments and return values: // in int -> int // out int -> int // return int -> int // in int array -> int[] // in string -> string // out string -> IntPtr (converted to string with Marshal.PtrToStringAnsi) // return string -> IntPtr (converted to string with Marshal.PtrToStringAnsi) // inout struct -> IntPtr (converted from/to struct with Marshal.PtrToStructure/Marshal.PtrToStructure // return struct -> IntPtr (converted to struct with Marshal.PtrToStructure) [DllImport("stddemolib.dll")] public static extern int std_add(int a, int b); [DllImport("stddemolib.dll")] public static extern int std_sum(int n, int[] a); [DllImport("stddemolib.dll")] public static extern IntPtr std_dup(string s); [DllImport("stddemolib.dll")] public static extern void std_get_out(out int iv, out IntPtr sv); [DllImport("stddemolib.dll")] public static extern IntPtr std_get_ret(); [DllImport("stddemolib.dll")] public static extern void std_chg(IntPtr p); [DllImport("stddemolib.dll")] public static extern void std_free(IntPtr s); public static void Main(string[] args) { int a = 123; int b = 456; int c = std_add(a, b); Console.WriteLine(c); // int[] six = { 1, 2, 3, 4, 5, 6 }; int allsix = std_sum(six.Length, six); Console.WriteLine(allsix); // string s = "ABC"; IntPtr temps = std_dup(s); string s2 = Marshal.PtrToStringAnsi(temps); Console.WriteLine(s2); std_free(temps); // int iv; IntPtr tempsv; std_get_out(out iv, out tempsv); string sv = Marshal.PtrToStringAnsi(tempsv); Console.WriteLine("{0} {1}", iv, sv); std_free(tempsv); // IntPtr p1 = std_get_ret(); MgData1 d1 = (MgData1)Marshal.PtrToStructure(p1, typeof(MgData1)); std_free(p1); Console.WriteLine("{0} {1}", d1.iv, d1.sv); // MgData2 d2 = new MgData2(); d2.iv1 = 123; d2.sv1 = "ABC"; IntPtr p2 = Marshal.AllocHGlobal(Marshal.SizeOf(d2)); Marshal.StructureToPtr(d2, p2, true); std_chg(p2); d2 = (MgData2)Marshal.PtrToStructure(p2, typeof(MgData2)); Console.WriteLine("{0} {1}", d2.iv2, d2.sv2); } }