diff options
| author | chai <215380520@qq.com> | 2023-11-25 18:39:02 +0800 |
|---|---|---|
| committer | chai <215380520@qq.com> | 2023-11-25 18:39:02 +0800 |
| commit | 0e63c4a2c6dec8dfa260501fb7d73750261ea7b7 (patch) | |
| tree | f6f2291be65d195d6082b523a56183c332715240 /Assembly_Firstpass/Steamworks/Callback.cs | |
+ init
Diffstat (limited to 'Assembly_Firstpass/Steamworks/Callback.cs')
| -rw-r--r-- | Assembly_Firstpass/Steamworks/Callback.cs | 106 |
1 files changed, 106 insertions, 0 deletions
diff --git a/Assembly_Firstpass/Steamworks/Callback.cs b/Assembly_Firstpass/Steamworks/Callback.cs new file mode 100644 index 0000000..fd7d84e --- /dev/null +++ b/Assembly_Firstpass/Steamworks/Callback.cs @@ -0,0 +1,106 @@ +using System; +using System.Runtime.InteropServices; + +namespace Steamworks; + +public abstract class Callback +{ + public abstract bool IsGameServer { get; } + + internal abstract Type GetCallbackType(); + + internal abstract void OnRunCallback(IntPtr pvParam); + + internal abstract void SetUnregistered(); +} +public sealed class Callback<T> : Callback, IDisposable +{ + public delegate void DispatchDelegate(T param); + + private bool m_bGameServer; + + private bool m_bIsRegistered; + + private bool m_bDisposed; + + public override bool IsGameServer => m_bGameServer; + + private event DispatchDelegate m_Func; + + public static Callback<T> Create(DispatchDelegate func) + { + return new Callback<T>(func); + } + + public static Callback<T> CreateGameServer(DispatchDelegate func) + { + return new Callback<T>(func, bGameServer: true); + } + + public Callback(DispatchDelegate func, bool bGameServer = false) + { + m_bGameServer = bGameServer; + Register(func); + } + + ~Callback() + { + Dispose(); + } + + public void Dispose() + { + if (!m_bDisposed) + { + GC.SuppressFinalize(this); + if (m_bIsRegistered) + { + Unregister(); + } + m_bDisposed = true; + } + } + + public void Register(DispatchDelegate func) + { + if (func == null) + { + throw new Exception("Callback function must not be null."); + } + if (m_bIsRegistered) + { + Unregister(); + } + this.m_Func = func; + CallbackDispatcher.Register(this); + m_bIsRegistered = true; + } + + public void Unregister() + { + CallbackDispatcher.Unregister(this); + m_bIsRegistered = false; + } + + internal override Type GetCallbackType() + { + return typeof(T); + } + + internal override void OnRunCallback(IntPtr pvParam) + { + try + { + this.m_Func((T)Marshal.PtrToStructure(pvParam, typeof(T))); + } + catch (Exception e) + { + CallbackDispatcher.ExceptionHandler(e); + } + } + + internal override void SetUnregistered() + { + m_bIsRegistered = false; + } +} |
