Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
1.4KB

  1. using System;
  2. using System.Runtime.InteropServices;
  3. namespace Svelto.ECS.Hybrid
  4. {
  5. /// <summary>
  6. /// an ECS dirty trick to hold the reference to an object. this is component can be used in an engine
  7. /// managing an OOP abstraction layer. It's need is quite rare though! An example is found at
  8. /// https://github.com/sebas77/Svelto.MiniExamples/blob/master/Example6-Unity%20Hybrid-OOP%20Abstraction/Assets/Code/WithEntityViewComponent/Descriptors/TransformImplementor.cs
  9. /// All other uses must be considered an abuse
  10. /// as the object can be casted back to it's real type only by an OOP Abstraction Layer Engine:
  11. /// https://www.sebaslab.com/oop-abstraction-layer-in-a-ecs-centric-application/
  12. /// </summary>
  13. /// <typeparam name="T"></typeparam>
  14. public struct ValueReference<T> : IDisposable where T:class, IImplementor
  15. {
  16. static ValueReference()
  17. {
  18. DBC.ECS.Check.Require(typeof(T).IsInterface == true, "ValueReference type can be only pure interface implementing IImplementor");
  19. }
  20. public ValueReference(T obj) { _pointer = GCHandle.Alloc(obj, GCHandleType.Normal); }
  21. public W Convert<W>(W implementer) where W:T
  22. {
  23. var pointerTarget = _pointer.Target;
  24. return (W)pointerTarget;
  25. }
  26. public void Dispose()
  27. {
  28. _pointer.Free();
  29. }
  30. GCHandle _pointer;
  31. }
  32. }