2003-06-11 Dietmar Maurer <dietmar@ximian.com>
[mono.git] / mono / tests / marshal10.cs
1 // A demonstration of a custom marshaler that marshals
2 // unmanaged to managed data.
3
4 using System;
5 using System.Runtime.InteropServices;
6
7 public class MyMarshal: ICustomMarshaler
8 {
9
10         // GetInstance() is not part of ICustomMarshaler, but
11         // custom marshalers are required to implement this
12         // method.
13         public static ICustomMarshaler GetInstance (string s)
14         {
15                 Console.WriteLine ("GetInstance called");
16                 return new MyMarshal ();
17         }
18         
19         public void CleanUpManagedData (object managedObj)
20         {
21                 Console.WriteLine ("CleanUpManagedData called");
22         }
23
24         public void CleanUpNativeData (IntPtr pNativeData)
25         {
26                 Console.WriteLine("CleanUpNativeData called");
27                 if (pNativeData != IntPtr.Zero)
28                         Marshal.FreeHGlobal (pNativeData);
29         }
30
31
32         // I really do not understand the purpose of this method
33         // or went it would be called. In fact, Rotor never seems
34         // to call it.
35         public int GetNativeDataSize ()
36         {
37                 Console.WriteLine("GetNativeDataSize() called");
38                 return 4;
39         }
40
41         public IntPtr MarshalManagedToNative (object managedObj)
42         {
43                 Console.WriteLine("MarshalManagedToNative()");
44                 return IntPtr.Zero;
45         }
46
47
48         // Convert a pointer to unmanaged data into a System.Object.
49         // This method simply converts the unmanaged Ansi C-string
50         // into a System.String and surrounds it with asterisks
51         // to differentiate it from the default marshaler.
52         public object MarshalNativeToManaged (IntPtr pNativeData)
53         {
54                 Console.WriteLine("MarshalNativeToManaged()");
55                 return "*" + Marshal.PtrToStringAnsi( pNativeData ) + "*";
56         }
57 }
58
59 public class Testing
60 {
61         [DllImport("libtest.so")]
62         [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MyMarshal))]
63         private static extern string functionReturningString();
64
65         public static int Main()
66         {
67                 string res = functionReturningString();
68                 Console.WriteLine ("native string function returns {0}", res);
69
70                 if (res != "*ABC*")
71                         return 1;
72                 return 0;
73         }
74
75
76
77 }