Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/Core/Silk.NET.Core/Miscellaneous/PfnVoidFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ namespace Silk.NET.Core
public static implicit operator nint(PfnVoidFunction pfn) => (nint) pfn.Handle;

public PfnVoidFunction
(Delegate func) => _handle = (delegate* unmanaged[Cdecl]<void>) SilkMarshal.DelegateToPtr
(func);
(Delegate func) => _handle = (delegate* unmanaged[Cdecl]<void>) SilkMarshal.DelegateToPtr<Delegate>(func);

public void Dispose() => SilkMarshal.Free((nint) _handle);
public static implicit operator delegate* unmanaged[Cdecl]<void>
Expand All @@ -25,4 +24,4 @@ public static implicit operator PfnVoidFunction

public static implicit operator PfnVoidFunction(Delegate func) => new(func);
}
}
}
26 changes: 26 additions & 0 deletions src/Core/Silk.NET.Core/Native/SilkMarshal.cs
Original file line number Diff line number Diff line change
Expand Up @@ -716,6 +716,32 @@ public static nint DelegateToPtr
static void ThrowManagedNonStatic()
=> throw new InvalidOperationException("Can't get a passthrough pointer to a non-static method group.");
}

/// <summary>
/// Gets a function pointer for the given delegate.
/// </summary>
/// <param name="delegate">The delegate to get a function pointer to.</param>
/// <param name="pinned">
/// Whether to pin the delegate such that the returned pointer remains valid for long periods of time.
/// </param>
/// <typeparam name="TDelegate">The delegate's type to marshal.</typeparam>
/// <returns>A function pointer to the given delegate.</returns>
public static nint DelegateToPtr<TDelegate>
(
TDelegate @delegate,
bool pinned = true
) where TDelegate : notnull
{
if (pinned)
{
var gcHandle = GCHandle.Alloc(@delegate);
var ret = Marshal.GetFunctionPointerForDelegate<TDelegate>(@delegate);
_otherGCHandles.TryAdd(ret, gcHandle);
return ret;
}

return Marshal.GetFunctionPointerForDelegate<TDelegate>(@delegate);
}

private static void DelegateSafetyCheck(Delegate @delegate, CallingConvention conv)
{
Expand Down
Loading