ClrHelper.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. namespace Jint.Runtime.Interop;
  2. using Jint.Native;
  3. public class ClrHelper
  4. {
  5. private readonly InteropOptions _interopOptions;
  6. internal ClrHelper(InteropOptions interopOptions)
  7. {
  8. _interopOptions = interopOptions;
  9. }
  10. /// <summary>
  11. /// Call JsValue.ToString(), mainly for NamespaceReference.
  12. /// </summary>
  13. public JsValue ToString(JsValue value)
  14. {
  15. return value.ToString();
  16. }
  17. /// <summary>
  18. /// Cast `obj as ISomeInterface` to `obj`
  19. /// </summary>
  20. public JsValue Unwrap(ObjectWrapper obj)
  21. {
  22. return new ObjectWrapper(obj.Engine, obj.Target);
  23. }
  24. /// <summary>
  25. /// Cast `obj` to `obj as ISomeInterface`
  26. /// </summary>
  27. public JsValue Wrap(ObjectWrapper obj, TypeReference type)
  28. {
  29. if (!type.ReferenceType.IsInstanceOfType(obj.Target))
  30. {
  31. ExceptionHelper.ThrowTypeError(type.Engine.Realm, "Argument obj must be an instance of type");
  32. }
  33. return new ObjectWrapper(obj.Engine, obj.Target, type.ReferenceType);
  34. }
  35. /// <summary>
  36. /// Get `TypeReference(ISomeInterface)` from `obj as ISomeInterface`
  37. /// </summary>
  38. public JsValue TypeOf(ObjectWrapper obj)
  39. {
  40. MustAllowGetType();
  41. return TypeReference.CreateTypeReference(obj.Engine, obj.ClrType);
  42. }
  43. /// <summary>
  44. /// Cast `TypeReference(SomeClass)` to `ObjectWrapper(SomeClass)`
  45. /// </summary>
  46. public JsValue TypeToObject(TypeReference type)
  47. {
  48. MustAllowGetType();
  49. var engine = type.Engine;
  50. return engine.Options.Interop.WrapObjectHandler.Invoke(engine, type.ReferenceType, null) ?? JsValue.Undefined;
  51. }
  52. /// <summary>
  53. /// Cast `ObjectWrapper(SomeClass)` to `TypeReference(SomeClass)`
  54. /// </summary>
  55. public JsValue ObjectToType(ObjectWrapper obj)
  56. {
  57. MustAllowGetType();
  58. if (obj.Target is Type t)
  59. {
  60. return TypeReference.CreateTypeReference(obj.Engine, t);
  61. }
  62. else
  63. {
  64. ExceptionHelper.ThrowArgumentException("Must be an ObjectWrapper of Type", "obj");
  65. }
  66. return JsValue.Undefined;
  67. }
  68. private void MustAllowGetType()
  69. {
  70. if (!_interopOptions.AllowGetType)
  71. {
  72. ExceptionHelper.ThrowInvalidOperationException("Invalid when Engine.Options.Interop.AllowGetType == false");
  73. }
  74. }
  75. }