forked from nwn-dotnet/Anvil
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionHook.cs
More file actions
51 lines (44 loc) · 1.37 KB
/
FunctionHook.cs
File metadata and controls
51 lines (44 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
using NWNX.NET;
using NWNX.NET.Native;
namespace Anvil.Services
{
public sealed unsafe class FunctionHook<T> : IDisposable where T : Delegate
{
/// <summary>
/// The original function call - invoke this to run the standard game behaviour.
/// </summary>
public readonly T CallOriginal;
// We hold a reference to the delegate to prevent clean up from the garbage collector.
[UsedImplicitly]
private readonly T? managedHandle;
private readonly HookService hookService;
private readonly FunctionHook* functionHook;
internal FunctionHook(HookService hookService, FunctionHook* functionHook, T? managedHandle = null)
{
this.hookService = hookService;
this.functionHook = functionHook;
this.managedHandle = managedHandle;
CallOriginal = Marshal.GetDelegateForFunctionPointer<T>((IntPtr)functionHook->m_trampoline);
}
private void ReleaseUnmanagedResources()
{
NWNXAPI.ReturnFunctionHook(functionHook);
}
/// <summary>
/// Releases the FunctionHook, restoring the previous behaviour.
/// </summary>
public void Dispose()
{
ReleaseUnmanagedResources();
GC.SuppressFinalize(this);
hookService.RemoveHook(this);
}
~FunctionHook()
{
ReleaseUnmanagedResources();
}
}
}