optimize handling of disposed hooks

This commit is contained in:
2023-10-06 21:00:17 +02:00
parent e01ebcde37
commit 0af7217e63
2 changed files with 13 additions and 7 deletions

View File

@@ -33,6 +33,8 @@ namespace Pilz.Dalamud.Nameplates
private Hook<AddonNamePlate_SetPlayerNameplateDetour>? hook_AddonNamePlate_SetPlayerNameplateDetour = null;
private unsafe delegate IntPtr AddonNamePlate_SetPlayerNameplateDetour(IntPtr playerNameplateObjectPtr, bool isTitleAboveName, bool isTitleVisible, IntPtr titlePtr, IntPtr namePtr, IntPtr freeCompanyPtr, IntPtr prefix, int iconId);
private bool allowHookHandling = false;
/// <summary>
/// Defines if all hooks are enabled. If this is false, then there might be something wrong or the class already has been disposed.
/// </summary>
@@ -64,6 +66,7 @@ namespace Pilz.Dalamud.Nameplates
public void Dispose()
{
Unhook();
GC.SuppressFinalize(this);
}
/// <summary>
@@ -71,7 +74,9 @@ namespace Pilz.Dalamud.Nameplates
/// </summary>
internal void Initialize()
{
if (!IsHookEnabled(hook_AddonNamePlate_SetPlayerNameplateDetour))
hook_AddonNamePlate_SetPlayerNameplateDetour?.Enable();
allowHookHandling = true;
}
/// <summary>
@@ -79,7 +84,9 @@ namespace Pilz.Dalamud.Nameplates
/// </summary>
internal void Unhook()
{
if (allowHookHandling && IsHookEnabled(hook_AddonNamePlate_SetPlayerNameplateDetour))
hook_AddonNamePlate_SetPlayerNameplateDetour?.Disable();
allowHookHandling = false;
}
private static bool IsHookEnabled<T>(Hook<T> hook) where T : Delegate
@@ -91,7 +98,7 @@ namespace Pilz.Dalamud.Nameplates
{
var result = IntPtr.Zero;
if (IsHookEnabled(hook_AddonNamePlate_SetPlayerNameplateDetour))
if (allowHookHandling && IsHookEnabled(hook_AddonNamePlate_SetPlayerNameplateDetour))
{
var eventArgs = new AddonNamePlate_SetPlayerNameEventArgs
{

View File

@@ -36,6 +36,7 @@ namespace Pilz.Dalamud.Nameplates
public void Dispose()
{
Hooks?.Dispose();
GC.SuppressFinalize(this);
}
public static T? GetNameplateGameObject<T>(SafeNameplateObject namePlateObject) where T : GameObject
@@ -49,19 +50,17 @@ namespace Pilz.Dalamud.Nameplates
var nameplateAddonPtr = PluginServices.GameGui.GetAddonByName("NamePlate", 1);
var nameplateObjectArrayPtrPtr = nameplateAddonPtr + Marshal.OffsetOf(typeof(AddonNamePlate), nameof(AddonNamePlate.NamePlateObjectArray)).ToInt32();
var nameplateObjectArrayPtr = Marshal.ReadIntPtr(nameplateObjectArrayPtrPtr);
if (nameplateObjectArrayPtr == IntPtr.Zero)
{
return null;
}
// Determine the index of the nameplate object within the nameplate object array
var namePlateObjectSize = Marshal.SizeOf(typeof(AddonNamePlate.NamePlateObject));
var namePlateObjectPtr0 = nameplateObjectArrayPtr + namePlateObjectSize * 0;
var namePlateIndex = (nameplateObjectPtr.ToInt64() - namePlateObjectPtr0.ToInt64()) / namePlateObjectSize;
if (namePlateIndex < 0 || namePlateIndex >= AddonNamePlate.NumNamePlateObjects)
{
return null;
}
// Get the nameplate info array
IntPtr nameplateInfoArrayPtr = IntPtr.Zero;