Is there equivalent to MonoPInvokeCallback in dotnet? #65296
-
I have been looking for solution to the callbackOnCollectedDelegate problem. Edit: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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 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
My basic understanding of the old delegate-marshaled-as-function-pointer method is that the runtime would dynamically create a stub which handles marshaling from the native calling convention to the managed calling convention. When these delegates get garbage collected these stubs get destroyed. When you're on an AOT-compiled platform that dynamic stub creation isn't possible, it has to be done ahead of time. |
Beta Was this translation helpful? Give feedback.
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); …