1 // A demonstration of a custom marshaler that marshals
2 // unmanaged to managed data.
5 using System.Runtime.InteropServices;
7 public class MyMarshal: ICustomMarshaler
10 // GetInstance() is not part of ICustomMarshaler, but
11 // custom marshalers are required to implement this
13 public static ICustomMarshaler GetInstance (string s)
15 Console.WriteLine ("GetInstance called");
16 return new MyMarshal ();
19 public void CleanUpManagedData (object managedObj)
21 Console.WriteLine ("CleanUpManagedData called");
24 public void CleanUpNativeData (IntPtr pNativeData)
26 Console.WriteLine("CleanUpNativeData called");
27 if (pNativeData != IntPtr.Zero)
28 Marshal.FreeHGlobal (pNativeData);
32 // I really do not understand the purpose of this method
33 // or went it would be called. In fact, Rotor never seems
35 public int GetNativeDataSize ()
37 Console.WriteLine("GetNativeDataSize() called");
41 public IntPtr MarshalManagedToNative (object managedObj)
47 number = Convert.ToInt32 (managedObj);
48 ptr = Marshal.AllocHGlobal (4);
49 Marshal.WriteInt32 (ptr, number);
57 // Convert a pointer to unmanaged data into a System.Object.
58 // This method simply converts the unmanaged Ansi C-string
59 // into a System.String and surrounds it with asterisks
60 // to differentiate it from the default marshaler.
61 public object MarshalNativeToManaged (IntPtr pNativeData)
63 return "*" + Marshal.PtrToStringAnsi( pNativeData ) + "*";
69 [DllImport("libtest")]
70 private static extern int printInt([MarshalAs( UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MyMarshal ))] object number );
72 [DllImport("libtest")]
73 private static extern void callFunction (Delegate d);
75 delegate void Del ([MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MyMarshal))] string x);
77 public static void TestMethod (string s)
79 Console.WriteLine("s = {0}", s);
81 throw new Exception ("received wrong value");
84 public static int Main()
87 if (printInt (x) != 6)
90 Del del = new Del (TestMethod);