Hi,
I've been coding a Wow framework for a good amount of time and I'm starting to think about refactoring my code since it's starting to be a maintenance hell. The biggest problem I have so far is in relation to statics. Basically, I'm using WhiteMagic by Apoc (awsome lib!!!), but so far I have a big drawback with it. In all of my code that uses hook, I have to use static delegates/classes.
Now, from what I understand, we have to do that to keep an instance of our delegate alive if we don't want it to be thrown away by the garbage collector. I've looked around on forums and blogs about what could be the solutions, and I've found the GCHandle class. The following method seems to be interesting :
public static GCHandle Alloc(Object value, GCHandleType type);
Basically, what I thought was to use this method to pin my delegates in instance classes (non-static). Let's take for e.g. an EndScene hook (doesn't include 100% of the code, only important parts).:
Code:
[UnmanagedFunctionPointer(CallingConvention.Winapi)]
public delegate int EndSceneDelegate(IntPtr instance);
private void SetupDirectxHook()
{
EndSceneDelegate EndSceneHandl = new EndSceneDelegate(EndSceneDetour);
// Call Free() later when necessary (most then likely on framework closing).
GCHandle.Alloc(EndSceneHandl, GCHandleType.Pinned);
IntPtr endScenePtr = GetDevicePointer((UInt32)Direct3DAPI.EndSceneOffset);
EndSceneDelegate EndSceneTypedef = Magic.Instance.RegisterDelegate<EndSceneDelegate>(endScenePtr);
Magic.Instance.Detours.CreateAndApply(EndSceneTypedef, EndSceneHandl, "EndScene");
}
private int EndSceneDetour(IntPtr instance)
{
return (int)Magic.Instance.Detours["EndScene"].CallOriginal(instance);
}
Now, this would get me rid of any statics. Now *IF* this works, the problem would be with certain type of parameters. GCHandle.Alloc throws a ArgumentException on the following case (quote from MSDN) : An instance with nonprimitive (non-blittable) members cannot be pinned.
Anyway, enought with my wall of text, are there cases where this wouldn't work, or why it wouldn't work?