Pointer.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Diagnostics;
  5. using System.Runtime.Serialization;
  6. namespace System.Reflection
  7. {
  8. [CLSCompliant(false)]
  9. public sealed unsafe class Pointer : ISerializable
  10. {
  11. // CoreCLR: Do not add or remove fields without updating the ReflectionPointer class in runtimehandles.h
  12. private readonly void* _ptr;
  13. private readonly Type _ptrType;
  14. private Pointer(void* ptr, Type ptrType)
  15. {
  16. Debug.Assert(ptrType.IsRuntimeImplemented()); // CoreCLR: For CoreRT's sake, _ptrType has to be declared as "Type", but in fact, it is always a RuntimeType. Code on CoreCLR expects this.
  17. _ptr = ptr;
  18. _ptrType = ptrType;
  19. }
  20. public static object Box(void* ptr, Type type)
  21. {
  22. if (type == null)
  23. throw new ArgumentNullException(nameof(type));
  24. if (!type.IsPointer)
  25. throw new ArgumentException(SR.Arg_MustBePointer, nameof(ptr));
  26. if (!type.IsRuntimeImplemented())
  27. throw new ArgumentException(SR.Arg_MustBeType, nameof(ptr));
  28. return new Pointer(ptr, type);
  29. }
  30. public static void* Unbox(object ptr)
  31. {
  32. if (!(ptr is Pointer))
  33. throw new ArgumentException(SR.Arg_MustBePointer, nameof(ptr));
  34. return ((Pointer)ptr)._ptr;
  35. }
  36. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
  37. {
  38. throw new PlatformNotSupportedException();
  39. }
  40. internal Type GetPointerType() => _ptrType;
  41. internal IntPtr GetPointerValue() => (IntPtr)_ptr;
  42. }
  43. }