You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

39 lines
989 B

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
public abstract class CallbackHandler<THandler>
where THandler: CallbackHandler<THandler>
{
private GCHandle selfHandle;
private List<GCHandle> delegateHandles = new List<GCHandle>();
public IntPtr SelfPtr => GCHandle.ToIntPtr(selfHandle);
protected CallbackHandler()
{
selfHandle = GCHandle.Alloc(this);
}
public virtual void Destroy()
{
foreach (var handle in delegateHandles)
{
if (handle.IsAllocated)
handle.Free();
}
selfHandle.Free();
}
protected IntPtr CreateCallback<TDelegate>(TDelegate callback)
{
delegateHandles.Add(GCHandle.Alloc(callback));
return Marshal.GetFunctionPointerForDelegate(callback);
}
protected static THandler GetSelf(IntPtr target)
{
return (THandler)GCHandle.FromIntPtr(target).Target;
}
}