2 // System.Runtime.InteropServices.Marshal Test Cases
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 // Sebastien Pouliot <sebastien@ximian.com>
8 // Copyright (C) 2004-2007 Novell, Inc (http://www.novell.com)
10 using NUnit.Framework;
13 using System.Reflection;
15 using System.Reflection.Emit;
17 using System.Runtime.InteropServices;
18 using System.Security;
21 namespace MonoTests.System.Runtime.InteropServices
24 public class MarshalTest
26 [StructLayout (LayoutKind.Sequential)]
31 public class ClsNoLayout {
35 [StructLayout (LayoutKind.Explicit)]
37 [FieldOffset (0)] public int field;
40 [StructLayout (LayoutKind.Sequential)]
41 struct StrSequential {
49 [StructLayout (LayoutKind.Explicit)]
51 [FieldOffset (0)] public int field;
55 public void SizeOf_Class_LayoutSequential ()
57 Marshal.SizeOf (typeof (ClsSequential));
61 public void SizeOf_Class_LayoutNotSet ()
64 Marshal.SizeOf (typeof (ClsNoLayout));
66 } catch (ArgumentException ex) {
67 // Type '...MarshalTest+ClsNoLayout' cannot be
68 // marshaled as an unmanaged structure; no
69 // meaningful size or offset can be computed
70 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
71 Assert.IsNull (ex.InnerException, "#3");
72 Assert.IsNotNull (ex.Message, "#4");
77 public void SizeOf_Class_LayoutExplicit ()
79 Marshal.SizeOf (typeof (ClsExplicit));
83 public void SizeOf_Struct_LayoutSequential ()
85 Marshal.SizeOf (typeof (StrSequential));
89 public void SizeOf_Struct_LayoutNotSet ()
91 Marshal.SizeOf (typeof (StrNoLayout));
95 public void SizeOf_Struct_LayoutExplicit ()
97 Marshal.SizeOf (typeof (StrExplicit));
101 public void SizeOf_Array ()
104 Marshal.SizeOf (typeof (string []));
106 } catch (ArgumentException ex) {
107 // Type 'System.String[]' cannot be marshaled
108 // as an unmanaged structure; no meaningful
109 // size or offset can be computed
110 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
111 Assert.IsNull (ex.InnerException, "#3");
112 Assert.IsNotNull (ex.Message, "#4");
117 public unsafe void Sizeof_Pointer ()
119 int size = Marshal.SizeOf (typeof (char*));
120 Assert.IsTrue (size == 4 || size == 8);
124 public void PtrToStringWithNull ()
126 Assert.IsNull (Marshal.PtrToStringAnsi (IntPtr.Zero), "A");
127 Assert.IsNull (Marshal.PtrToStringUni (IntPtr.Zero), "C");
131 public void PtrToStringAnsi_Ptr_Zero ()
134 Marshal.PtrToStringAnsi (IntPtr.Zero, 0);
136 } catch (ArgumentNullException ex) {
137 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
138 Assert.IsNull (ex.InnerException, "#3");
139 Assert.IsNotNull (ex.Message, "#4");
140 Assert.AreEqual ("ptr", ex.ParamName, "#5");
145 public void PtrToStringWithUni_Ptr_Zero ()
148 Marshal.PtrToStringUni (IntPtr.Zero, 0);
150 } catch (ArgumentNullException ex) {
151 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
152 Assert.IsNull (ex.InnerException, "#3");
153 Assert.IsNotNull (ex.Message, "#4");
154 Assert.AreEqual ("ptr", ex.ParamName, "#5");
158 readonly String[] TestStrings = new String[] {
161 "A", //Single character string
162 "This is a very long string as it repeats itself. " +
163 "This is a very long string as it repeats itself. " +
164 "This is a very long string as it repeats itself. " +
165 "This is a very long string as it repeats itself. " +
166 "This is a very long string as it repeats itself. " +
167 "This is a very long string as it repeats itself. " +
168 "This is a very long string as it repeats itself. " +
169 "This is a very long string as it repeats itself. " +
170 "This is a very long string as it repeats itself. " +
171 "This is a very long string as it repeats itself. " +
172 "This is a very long string as it repeats itself. " +
173 "This is a very long string as it repeats itself. " +
174 "This is a very long string as it repeats itself.",
175 "This \n is \n a \n multiline \n string",
176 "This \0 is \0 a \0 string \0 with \0 nulls",
183 public unsafe void PtrToStringUTF8_Test ()
186 foreach (String srcString in TestStrings)
189 // we assume string null terminated
190 if (srcString.Contains("\0"))
193 IntPtr ptrString = Marshal.StringToAllocatedMemoryUTF8(srcString);
194 string retString = Marshal.PtrToStringUTF8(ptrString);
196 Assert.AreEqual (srcString, retString, "#" + i);
197 if (srcString.Length > 0)
199 string retString2 = Marshal.PtrToStringUTF8(ptrString, srcString.Length - 1);
200 Assert.AreEqual (srcString.Substring(0, srcString.Length - 1), retString2, "#s" + i);
202 Marshal.FreeHGlobal(ptrString);
207 public unsafe void UnsafeAddrOfPinnedArrayElement ()
209 short[] sarr = new short [5];
212 IntPtr ptr = Marshal.UnsafeAddrOfPinnedArrayElement (sarr, 2);
213 Assert.AreEqual (3, *(short*) ptr.ToPointer ());
217 public void AllocHGlobalZeroSize ()
219 IntPtr ptr = Marshal.AllocHGlobal (0);
220 Assert.IsTrue (ptr != IntPtr.Zero);
221 Marshal.FreeHGlobal (ptr);
225 public void AllocCoTaskMemZeroSize ()
227 IntPtr ptr = Marshal.AllocCoTaskMem (0);
228 Assert.IsTrue (ptr != IntPtr.Zero);
229 Marshal.FreeCoTaskMem (ptr);
236 public static char d;
241 public void OffsetOf_FieldName_Static ()
244 Marshal.OffsetOf (typeof (Foo), "b");
246 } catch (ArgumentException ex) {
247 // Field passed in is not a marshaled member of
248 // the type '...MarshalTest+Foo'
249 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
250 Assert.IsNull (ex.InnerException, "#3");
251 Assert.IsNotNull (ex.Message, "#4");
252 Assert.AreEqual ("fieldName", ex.ParamName, "#5");
257 public void GetHINSTANCE ()
260 Assert.Ignore ("GetHINSTANCE only applies to .NET on Windows.");
264 StringBuilder fileName;
266 fileName = new StringBuilder (255);
267 a = Assembly.GetExecutingAssembly ();
268 hinstance = Marshal.GetHINSTANCE (a.GetModules () [0]);
269 Assert.IsTrue (GetModuleFileName (hinstance, fileName,
270 fileName.Capacity) > 0, "#A1");
271 Assert.AreEqual (a.Location, fileName.ToString (), "#A2");
274 a = typeof (int).Assembly;
275 hinstance = Marshal.GetHINSTANCE (a.GetModules () [0]);
276 Assert.IsTrue (GetModuleFileName (hinstance, fileName,
277 fileName.Capacity) > 0, "#B1");
278 Assert.IsTrue (File.Exists (fileName.ToString ()), "#B3");
279 Assert.AreEqual ("mscorlib.dll", Path.GetFileName (fileName.ToString ()), "#B4");
283 public void GetHINSTANCE_Module_Dynamic ()
285 AssemblyName aname = new AssemblyName ();
288 AssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly (
289 aname, AssemblyBuilderAccess.Save,
290 Path.GetTempPath ());
291 ModuleBuilder mb = ab.DefineDynamicModule ("foo.dll", false);
293 IntPtr hinstance = Marshal.GetHINSTANCE (mb);
294 Assert.AreEqual (-1, hinstance.ToInt32 ());
298 public void GetHINSTANCE_Module_Null ()
301 Marshal.GetHINSTANCE ((Module) null);
303 } catch (ArgumentNullException ex) {
304 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
305 Assert.IsNull (ex.InnerException, "#3");
306 Assert.IsNotNull (ex.Message, "#4");
307 Assert.AreEqual ("m", ex.ParamName, "#5");
313 public void GetHRForException ()
315 Assert.AreEqual (0, Marshal.GetHRForException (null));
316 Assert.IsTrue (Marshal.GetHRForException (new Exception ()) < 0);
317 Assert.AreEqual (12345, Marshal.GetHRForException (new IOException ("test message", 12345)));
320 [Test] // bug #319009
321 public void StringToHGlobalUni ()
323 IntPtr handle = Marshal.StringToHGlobalUni ("unicode data");
324 string s = Marshal.PtrToStringUni (handle);
325 Assert.AreEqual (12, s.Length, "#1");
327 handle = Marshal.StringToHGlobalUni ("unicode data string");
328 s = Marshal.PtrToStringUni (handle);
329 Assert.AreEqual (19, s.Length, "#2");
333 public void ReadIntByte ()
335 IntPtr ptr = Marshal.AllocHGlobal (4);
337 Marshal.WriteByte (ptr, 0, 0x1);
338 Marshal.WriteByte (ptr, 1, 0x2);
339 Assert.AreEqual (0x1, Marshal.ReadByte (ptr));
340 Assert.AreEqual (0x1, Marshal.ReadByte (ptr, 0));
341 Assert.AreEqual (0x2, Marshal.ReadByte (ptr, 1));
343 Marshal.FreeHGlobal (ptr);
348 public void ReadInt16 ()
350 IntPtr ptr = Marshal.AllocHGlobal (64);
352 Marshal.WriteInt16 (ptr, 0, 0x1234);
353 Marshal.WriteInt16 (ptr, 2, 0x4567);
354 Marshal.WriteInt16 (ptr, 5, 0x4567);
355 Assert.AreEqual (0x1234, Marshal.ReadInt16 (ptr));
356 Assert.AreEqual (0x1234, Marshal.ReadInt16 (ptr, 0));
357 Assert.AreEqual (0x4567, Marshal.ReadInt16 (ptr, 2));
358 Assert.AreEqual (0x4567, Marshal.ReadInt16 ((ptr + 5)));
359 Assert.AreEqual (0x4567, Marshal.ReadInt16 (ptr, 5));
361 Marshal.FreeHGlobal (ptr);
366 public void ReadInt32 ()
368 IntPtr ptr = Marshal.AllocHGlobal (64);
370 Marshal.WriteInt32 (ptr, 0, 0x12345678);
371 Marshal.WriteInt32 (ptr, 4, 0x77654321);
372 Marshal.WriteInt32 (ptr, 10, 0x77654321);
373 Assert.AreEqual (0x12345678, Marshal.ReadInt32 (ptr));
374 Assert.AreEqual (0x12345678, Marshal.ReadInt32 (ptr, 0));
375 Assert.AreEqual (0x77654321, Marshal.ReadInt32 (ptr, 4));
376 Assert.AreEqual (0x77654321, Marshal.ReadInt32 ((ptr + 10)));
377 Assert.AreEqual (0x77654321, Marshal.ReadInt32 (ptr, 10));
379 Marshal.FreeHGlobal (ptr);
384 public void ReadInt32_Endian ()
386 IntPtr ptr = Marshal.AllocHGlobal (4);
388 Marshal.WriteByte (ptr, 0, 0x01);
389 Marshal.WriteByte (ptr, 1, 0x02);
390 Marshal.WriteByte (ptr, 2, 0x03);
391 Marshal.WriteByte (ptr, 3, 0x04);
392 // Marshal MUST use the native CPU data
393 if (BitConverter.IsLittleEndian){
394 Assert.AreEqual (0x04030201, Marshal.ReadInt32 (ptr), "ReadInt32");
396 Assert.AreEqual (0x01020304, Marshal.ReadInt32 (ptr), "ReadInt32");
399 Marshal.FreeHGlobal (ptr);
404 public void ReadInt64 ()
406 IntPtr ptr = Marshal.AllocHGlobal (16);
408 Marshal.WriteInt64 (ptr, 0, 0x12345678ABCDEFL);
409 Marshal.WriteInt64 (ptr, 8, 0x87654321ABCDEFL);
410 Assert.AreEqual (0x12345678ABCDEFL, Marshal.ReadInt64 (ptr));
411 Assert.AreEqual (0x12345678ABCDEFL, Marshal.ReadInt64 (ptr, 0));
412 Assert.AreEqual (0x87654321ABCDEFL, Marshal.ReadInt64 (ptr, 8));
414 Marshal.FreeHGlobal (ptr);
419 public void BSTR_Roundtrip ()
422 IntPtr ptr = Marshal.StringToBSTR (s);
423 string s2 = Marshal.PtrToStringBSTR (ptr);
424 Assert.AreEqual (s, s2, "string");
428 public void StringToBSTRWithNullValues ()
431 string s = String.Empty.PadLeft (size, '\0');
432 Assert.AreEqual (size, s.Length, "Length-1");
434 IntPtr ptr = Marshal.StringToBSTR (s);
436 for (int i = 0; i < size; i += 4)
437 Marshal.WriteInt32 (ptr, i, 0);
439 string s2 = Marshal.PtrToStringBSTR (ptr);
440 Assert.AreEqual (128, s2.Length, "Length-2");
442 Marshal.FreeBSTR (ptr);
447 public void StringToHGlobalAnsiWithNullValues ()
450 string s = String.Empty.PadLeft (size, '\0');
451 Assert.AreEqual (size, s.Length, "Length-1");
453 IntPtr ptr = Marshal.StringToHGlobalAnsi (s);
455 for (int i = 0; i < size; i += 4)
456 Marshal.WriteInt32 (ptr, i, 0);
458 string s2 = Marshal.PtrToStringAnsi (ptr);
459 Assert.AreEqual (0, s2.Length, "Length-2");
461 Marshal.FreeHGlobal (ptr);
466 public void StringToHGlobalAutoWithNullValues ()
469 string s = String.Empty.PadLeft (size, '\0');
470 Assert.AreEqual (size, s.Length, "Length-1");
472 IntPtr ptr = Marshal.StringToHGlobalAuto (s);
474 for (int i = 0; i < size; i += 4)
475 Marshal.WriteInt32 (ptr, i, 0);
477 string s2 = Marshal.PtrToStringAuto (ptr);
478 Assert.AreEqual (0, s2.Length, "Length-2");
480 Marshal.FreeHGlobal (ptr);
485 public void StringToHGlobalUniWithNullValues ()
488 string s = String.Empty.PadLeft (size, '\0');
489 Assert.AreEqual (size, s.Length, "Length-1");
491 IntPtr ptr = Marshal.StringToHGlobalUni (s);
493 for (int i = 0; i < size; i += 4)
494 Marshal.WriteInt32 (ptr, i, 0);
496 string s2 = Marshal.PtrToStringUni (ptr);
497 Assert.AreEqual (0, s2.Length, "Length-2");
499 Marshal.FreeHGlobal (ptr);
504 public void StringToCoTaskMemAnsiWithNullValues ()
507 string s = String.Empty.PadLeft (size, '\0');
508 Assert.AreEqual (size, s.Length, "Length-1");
510 IntPtr ptr = Marshal.StringToCoTaskMemAnsi (s);
512 for (int i = 0; i < size; i += 4)
513 Marshal.WriteInt32 (ptr, i, 0);
515 string s2 = Marshal.PtrToStringAnsi (ptr);
516 Assert.AreEqual (0, s2.Length, "Length-2");
518 Marshal.FreeCoTaskMem (ptr);
523 public void StringToCoTaskMemAutoWithNullValues ()
526 string s = String.Empty.PadLeft (size, '\0');
527 Assert.AreEqual (size, s.Length, "Length-1");
529 IntPtr ptr = Marshal.StringToCoTaskMemAuto (s);
531 for (int i = 0; i < size; i += 4)
532 Marshal.WriteInt32 (ptr, i, 0);
534 string s2 = Marshal.PtrToStringAuto (ptr);
535 Assert.AreEqual (0, s2.Length, "Length-2");
537 Marshal.FreeCoTaskMem (ptr);
542 public void StringToCoTaskMemUniWithNullValues ()
545 string s = String.Empty.PadLeft (size, '\0');
546 Assert.AreEqual (size, s.Length, "Length-1");
548 IntPtr ptr = Marshal.StringToCoTaskMemUni (s);
550 for (int i = 0; i < size; i += 4)
551 Marshal.WriteInt32 (ptr, i, 0);
553 string s2 = Marshal.PtrToStringUni (ptr);
554 Assert.AreEqual (0, s2.Length, "Length-2");
556 Marshal.FreeCoTaskMem (ptr);
559 private const string NotSupported = "Not supported before Windows 2000 Service Pack 3";
560 private static char[] PlainText = new char[] { 'a', 'b', 'c' };
561 private static byte[] AsciiPlainText = new byte[] { (byte) 'a', (byte) 'b', (byte) 'c' };
563 private unsafe SecureString GetSecureString ()
565 fixed (char* p = &PlainText[0]) {
566 return new SecureString (p, PlainText.Length);
571 public void SecureStringToBSTR_Null ()
574 Marshal.SecureStringToBSTR (null);
576 } catch (ArgumentNullException ex) {
577 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
578 Assert.IsNull (ex.InnerException, "#3");
579 Assert.IsNotNull (ex.Message, "#4");
580 Assert.AreEqual ("s", ex.ParamName, "#5");
585 public void SecureStringToBSTR ()
588 SecureString ss = GetSecureString ();
589 IntPtr p = Marshal.SecureStringToBSTR (ss);
591 char[] decrypted = new char[ss.Length];
592 Marshal.Copy (p, decrypted, 0, decrypted.Length);
593 Assert.AreEqual (PlainText, decrypted, "Decrypted");
595 Marshal.ZeroFreeBSTR (p);
596 } catch (NotSupportedException) {
597 Assert.Ignore (NotSupported);
602 public void SecureStringToCoTaskMemAnsi_Null ()
605 Marshal.SecureStringToCoTaskMemAnsi (null);
607 } catch (ArgumentNullException ex) {
608 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
609 Assert.IsNull (ex.InnerException, "#3");
610 Assert.IsNotNull (ex.Message, "#4");
611 Assert.AreEqual ("s", ex.ParamName, "#5");
616 public void SecureStringToCoTaskMemAnsi ()
619 SecureString ss = GetSecureString ();
620 IntPtr p = Marshal.SecureStringToCoTaskMemAnsi (ss);
622 byte[] decrypted = new byte[ss.Length];
623 Marshal.Copy (p, decrypted, 0, decrypted.Length);
624 Assert.AreEqual (AsciiPlainText, decrypted, "Decrypted");
626 Marshal.ZeroFreeCoTaskMemAnsi (p);
627 } catch (NotSupportedException) {
628 Assert.Ignore (NotSupported);
633 public void SecureStringToCoTaskMemUnicode_Null ()
636 Marshal.SecureStringToCoTaskMemUnicode (null);
638 } catch (ArgumentNullException ex) {
639 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
640 Assert.IsNull (ex.InnerException, "#3");
641 Assert.IsNotNull (ex.Message, "#4");
642 Assert.AreEqual ("s", ex.ParamName, "#5");
647 public void SecureStringToCoTaskMemUnicode ()
650 SecureString ss = GetSecureString ();
651 IntPtr p = Marshal.SecureStringToCoTaskMemUnicode (ss);
653 char[] decrypted = new char[ss.Length];
654 Marshal.Copy (p, decrypted, 0, decrypted.Length);
655 Assert.AreEqual (PlainText, decrypted, "Decrypted");
657 Marshal.ZeroFreeCoTaskMemUnicode (p);
658 } catch (NotSupportedException) {
659 Assert.Ignore (NotSupported);
664 public void SecureStringToGlobalAllocAnsi_Null ()
667 Marshal.SecureStringToGlobalAllocAnsi (null);
669 } catch (ArgumentNullException ex) {
670 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
671 Assert.IsNull (ex.InnerException, "#3");
672 Assert.IsNotNull (ex.Message, "#4");
673 Assert.AreEqual ("s", ex.ParamName, "#5");
678 public void SecureStringToGlobalAllocAnsi ()
681 SecureString ss = GetSecureString ();
682 IntPtr p = Marshal.SecureStringToGlobalAllocAnsi (ss);
684 byte[] decrypted = new byte[ss.Length];
685 Marshal.Copy (p, decrypted, 0, decrypted.Length);
686 Assert.AreEqual (AsciiPlainText, decrypted, "Decrypted");
688 Marshal.ZeroFreeGlobalAllocAnsi (p);
689 } catch (NotSupportedException) {
690 Assert.Ignore (NotSupported);
695 public void SecureStringToGlobalAllocUnicode_Null ()
698 Marshal.SecureStringToGlobalAllocUnicode (null);
700 } catch (ArgumentNullException ex) {
701 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
702 Assert.IsNull (ex.InnerException, "#3");
703 Assert.IsNotNull (ex.Message, "#4");
704 Assert.AreEqual ("s", ex.ParamName, "#5");
709 public void SecureStringToGlobalAllocUnicode ()
712 SecureString ss = GetSecureString ();
713 IntPtr p = Marshal.SecureStringToGlobalAllocUnicode (ss);
715 char[] decrypted = new char[ss.Length];
716 Marshal.Copy (p, decrypted, 0, decrypted.Length);
717 Assert.AreEqual (PlainText, decrypted, "Decrypted");
719 Marshal.ZeroFreeGlobalAllocUnicode (p);
720 } catch (NotSupportedException) {
721 Assert.Ignore (NotSupported);
727 public void TestGetComSlotForMethodInfo ()
729 Assert.AreEqual (7, Marshal.GetComSlotForMethodInfo(typeof(ITestDefault).GetMethod("DoNothing")));
730 Assert.AreEqual (7, Marshal.GetComSlotForMethodInfo(typeof(ITestDual).GetMethod("DoNothing")));
731 Assert.AreEqual (7, Marshal.GetComSlotForMethodInfo (typeof(ITestDefault).GetMethod ("DoNothing")));
732 Assert.AreEqual (3, Marshal.GetComSlotForMethodInfo (typeof(ITestUnknown).GetMethod ("DoNothing")));
734 for (int i = 0; i < 10; i++)
735 Assert.AreEqual (7+i, Marshal.GetComSlotForMethodInfo(typeof(ITestInterface).GetMethod ("Method"+i.ToString())));
739 public void TestGetComSlotForMethod_Method_Null ()
742 Marshal.GetComSlotForMethodInfo (null);
744 } catch (ArgumentNullException ex) {
745 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
746 Assert.IsNull (ex.InnerException, "#3");
747 Assert.IsNotNull (ex.Message, "#4");
748 Assert.AreEqual ("m", ex.ParamName, "#5");
753 public void TestGetComSlotForMethodInfo_Method_NotOnInterface ()
755 MethodInfo m = typeof(TestCoClass).GetMethod ("DoNothing");
757 Marshal.GetComSlotForMethodInfo (m);
759 } catch (ArgumentException ex) {
760 // The MemberInfo must be an interface method
761 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
762 Assert.IsNull (ex.InnerException, "#3");
763 Assert.IsNotNull (ex.Message, "#4");
764 Assert.AreEqual ("m", ex.ParamName, "#5");
769 public void TestPtrToStringAuto ()
771 string input = Guid.NewGuid ().ToString ();
777 if (Environment.OSVersion.Platform == PlatformID.Win32NT) {
779 ptr = Marshal.StringToHGlobalAuto (input);
780 output = Marshal.PtrToStringUni (ptr);
781 output2 = Marshal.PtrToStringUni (ptr, len);
784 ptr = Marshal.StringToHGlobalAuto (input);
785 output = Marshal.PtrToStringAnsi (ptr);
786 output2 = Marshal.PtrToStringAnsi (ptr, len);
790 Assert.AreEqual (input, output, "#1");
791 Assert.AreEqual (input.Substring (0, len), output2, "#2");
793 Marshal.FreeHGlobal (ptr);
798 public void TestGenerateProgIdForType()
802 output = Marshal.GenerateProgIdForType(typeof(TestCoClass));
803 Assert.AreEqual ("MonoTests.System.Runtime.InteropServices.TestCoClass", output, "#1");
805 output = Marshal.GenerateProgIdForType(typeof(TestCoClassWithProgId));
806 Assert.AreEqual ("CoClassWithProgId", output, "#2");
810 public void TestGlobalAlloc ()
812 IntPtr mem = Marshal.AllocHGlobal (100);
813 mem = Marshal.ReAllocHGlobal (mem, (IntPtr) 1000000);
814 Marshal.FreeHGlobal (mem);
818 public void FreeHGlobal ()
820 // clear user doubts on assistly #6749
821 for (int i = 0; i < 1024; i++) {
822 IntPtr p = Marshal.AllocHGlobal (1024 * 1024);
823 Assert.AreNotEqual (IntPtr.Zero, p, i.ToString ());
824 Marshal.FreeHGlobal (p);
828 [StructLayout (LayoutKind.Sequential)]
829 public struct SimpleStruct2 {
835 public void PtrToStructureNull ()
837 Assert.IsNull (Marshal.PtrToStructure (IntPtr.Zero, typeof (SimpleStruct2)));
841 public void TestGetExceptionForHR ()
843 const int E_OUTOFMEMORY = unchecked ((int) 0x8007000E);
844 const int E_INVALIDARG = unchecked ((int) 0X80070057);
846 Exception ex = Marshal.GetExceptionForHR (E_OUTOFMEMORY);
847 Assert.AreEqual (typeof (OutOfMemoryException), ex.GetType (), "E_OUTOFMEMORY");
849 ex = Marshal.GetExceptionForHR (E_INVALIDARG);
850 Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "E_INVALIDARG");
854 return (Type.GetType ("System.MonoType", false) != null);
859 [DllImport ("kernel32.dll", SetLastError = true)]
861 static extern uint GetModuleFileName (
865 StringBuilder lpFilename,
867 [MarshalAs (UnmanagedType.U4)]
872 #if !FULL_AOT_RUNTIME
873 [StructLayout( LayoutKind.Sequential, Pack = 1 )]
874 public class FourByteStruct
876 public UInt16 value1;
877 public UInt16 value2;
880 [StructLayout( LayoutKind.Sequential, Pack = 1 )]
881 public class ByteArrayFourByteStruct : FourByteStruct
883 [MarshalAs( UnmanagedType.ByValArray, SizeConst = 5 )]
887 [StructLayout( LayoutKind.Sequential, Pack = 1 )]
888 public class SingleByteStruct
893 [StructLayout( LayoutKind.Sequential, Pack = 1 )]
894 public class ByteArraySingleByteStruct : SingleByteStruct
896 [MarshalAs( UnmanagedType.ByValArray, SizeConst = 5 )]
897 public byte[] array1;
901 [StructLayout( LayoutKind.Sequential, Pack = 1 )]
902 public class ByteArraySingleByteChildStruct : ByteArraySingleByteStruct
904 [MarshalAs( UnmanagedType.ByValArray, SizeConst = 5 )]
905 public byte[] array2;
909 public void CheckByteArrayFourByteStruct()
911 ByteArrayFourByteStruct myStruct = new ByteArrayFourByteStruct
912 { value1 = 42, value2 = 53, array = Encoding.UTF8.GetBytes( "Hello" ) };
914 byte[] buffer = Serialize (myStruct);
916 UInt16 value1 = BitConverter.ToUInt16 (buffer, 0);
917 UInt16 value2 = BitConverter.ToUInt16 (buffer, 2);
918 string array = Encoding.UTF8.GetString (buffer, 4, 5);
920 Assert.AreEqual((UInt16)42, value1);
921 Assert.AreEqual((UInt16)53, value2);
922 Assert.AreEqual ("Hello", array);
926 public void CheckByteArraySingleByteChildStruct()
928 ByteArraySingleByteChildStruct myStruct = new ByteArraySingleByteChildStruct
929 { value1 = 42, array1 = Encoding.UTF8.GetBytes( "Hello" ), value2 = 53, array2 = Encoding.UTF8.GetBytes( "World" ) };
931 byte[] array = Serialize (myStruct);
933 byte value1 = array [0];
934 string array1 = Encoding.UTF8.GetString (array, 1, 5);
935 byte value2 = array [6];
936 string array2 = Encoding.UTF8.GetString (array, 7, 5);
938 Assert.AreEqual((byte)42, value1);
939 Assert.AreEqual ("Hello", array1);
940 Assert.AreEqual((byte)53, value2);
941 Assert.AreEqual ("World", array2);
944 [StructLayout(LayoutKind.Sequential, Pack = 1)]
945 public struct FiveByteStruct
947 public uint uIntField;
948 public byte byteField;
951 [StructLayout(LayoutKind.Sequential, Pack = 1)]
954 public ushort firstUShortField;
955 public ushort secondUShortField;
958 [StructLayout(LayoutKind.Sequential, Pack = 1)]
959 public class Derived : Base
961 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
962 public FiveByteStruct[] arrayField;
966 public void CheckPtrToStructureWithFixedArrayAndBaseClassFields()
968 const int arraySize = 6;
969 var derived = new Derived
971 arrayField = new FiveByteStruct[arraySize],
972 firstUShortField = 42,
973 secondUShortField = 43
976 for (var i = 0; i < arraySize; ++i)
978 derived.arrayField[i].byteField = (byte)i;
979 derived.arrayField[i].uIntField = (uint)i * 10;
982 var array = Serialize(derived);
983 var deserializedDerived = Deserialize<Derived>(array);
985 Assert.AreEqual(derived.firstUShortField, deserializedDerived.firstUShortField, "The firstUShortField differs, which is not expected.");
986 Assert.AreEqual(derived.secondUShortField, deserializedDerived.secondUShortField, "The secondUShortField differs, which is not expected.");
988 for (var i = 0; i < arraySize; ++i)
990 Assert.AreEqual(derived.arrayField[i].byteField, deserializedDerived.arrayField[i].byteField, string.Format("The byteField at index {0} differs, which is not expected.", i));
991 Assert.AreEqual(derived.arrayField[i].uIntField, deserializedDerived.arrayField[i].uIntField, string.Format("The uIntField at index {0} differs, which is not expected.", i));
995 public static byte[] Serialize( object obj )
997 int nTypeSize = Marshal.SizeOf( obj );
998 byte[] arrBuffer = new byte[nTypeSize];
1000 GCHandle hGCHandle = GCHandle.Alloc( arrBuffer, GCHandleType.Pinned );
1001 IntPtr pBuffer = hGCHandle.AddrOfPinnedObject();
1002 Marshal.StructureToPtr( obj, pBuffer, false );
1008 public static T Deserialize<T>(byte[] buffer)
1010 var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
1011 var pBuffer = handle.AddrOfPinnedObject();
1012 var objResult = (T)Marshal.PtrToStructure(pBuffer, typeof(T));
1021 [Guid("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA")]
1022 interface ITestDefault
1028 [Guid("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA")]
1029 [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
1030 interface ITestDispatch
1036 [Guid("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA")]
1037 [InterfaceType(ComInterfaceType.InterfaceIsDual)]
1044 [Guid("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA")]
1045 [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
1046 interface ITestUnknown
1052 [Guid("AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA")]
1053 interface ITestInterface
1067 public class TestCoClass : ITestDispatch
1069 public void DoNothing ()
1074 [ProgId("CoClassWithProgId")]
1075 public class TestCoClassWithProgId : ITestDispatch
1077 public void DoNothing ()