Skip to content

Are [UnmanagedCallersOnly] methods implicitly pinned? #108752

Answered by AustinWise
colejohnson66 asked this question in Q&A
Discussion options

You must be logged in to vote

From the blog post originally announcing the feature:

The extra error-prone code for keeping the delegate alive is no longer needed either.

Like @huoyaoyuan mentioned, the one exception you might have to worry about is if your assembly is loaded into an unloadable assembly load context. If you try to call an UnmanagedCallersOnly function after the assembly that defines it has been unloaded, you will crash. You can use the AssemblyLoadContext.Unloading event to clean up callbacks to prevent this crash.

Here is a small program that demonstrates how to do the cleanup:

https://gist.github.com/AustinWise/92f48f2f4c1ce04795599822a7aced89

It calls the Windows function RegisterWaitForSingleObject

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
2 replies
@colejohnson66
Comment options

@huoyaoyuan
Comment options

Comment options

You must be logged in to vote
2 replies
@colejohnson66
Comment options

@AustinWise
Comment options

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