Skip to content

Is there equivalent to MonoPInvokeCallback in dotnet? #65296

Answered by PathogenDavid
you74674 asked this question in Q&A
Discussion options

You must be logged in to vote

Instead of using delegates marshaled as function pointers you should just use C# 9's function pointers instead. (In which case the equivalent attribute would be UnamangedCallersOnly.)

If you're on an older pre-.NET 5 runtime and need to use delegates, you need to ensure the delegate does not get garbage collected when not in use. If the delegate is long-lived or will be reused many times the easiest way is to save it in a static field somewhere. If it's short lived (such as a callback that will only be used for the duration of a native function call) use GC.KeepAlive to ensure it survives until after the function call is completed. (IE: MyCallback cb = MyFunction; SomeNativeFunction(cb); …

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@you74674
Comment options

Answer selected by you74674
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants