Signal.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace Avalonia.Gtk3.Interop
  8. {
  9. public class Signal
  10. {
  11. class ConnectedSignal : IDisposable
  12. {
  13. private readonly IntPtr _instance;
  14. private GCHandle _handle;
  15. private readonly ulong _id;
  16. public ConnectedSignal(IntPtr instance, GCHandle handle, ulong id)
  17. {
  18. _instance = instance;
  19. _handle = handle;
  20. _id = id;
  21. }
  22. public void Dispose()
  23. {
  24. if (_handle.IsAllocated)
  25. {
  26. Native.GSignalHandlerDisconnect(_instance, _id);
  27. _handle.Free();
  28. }
  29. }
  30. }
  31. public static IDisposable Connect<T>(IntPtr obj, string name, T handler)
  32. {
  33. var handle = GCHandle.Alloc(handler);
  34. var ptr = Marshal.GetFunctionPointerForDelegate((Delegate)(object)handler);
  35. using (var utf = new Utf8Buffer(name))
  36. {
  37. var id = Native.GSignalConnectObject(obj, utf, ptr, IntPtr.Zero, 0);
  38. if (id == 0)
  39. throw new ArgumentException("Unable to connect to signal " + name);
  40. return new ConnectedSignal(obj, handle, id);
  41. }
  42. }
  43. }
  44. }