Skip to content

Update how-to-marshal-callbacks-and-delegates-by-using-cpp-interop.md #3466

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 21, 2021
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ The following example demonstrates how to configure an unmanaged API to trigger

Notice that is it possible, but not necessary, to pin the delegate using [pin_ptr (C++/CLI)](../extensions/pin-ptr-cpp-cli.md) to prevent it from being re-located or disposed of by the garbage collector. Protection from premature garbage collection is needed, but pinning provides more protection than is necessary, as it prevents collection but also prevents relocation.

If a delegate is re-located by a garbage collection, it will not affect the underlaying managed callback, so <xref:System.Runtime.InteropServices.GCHandle.Alloc%2A> is used to add a reference to the delegate, allowing relocation of the delegate, but preventing disposal. Using GCHandle instead of pin_ptr reduces fragmentation potential of the managed heap.
If a delegate is re-located by a garbage collection, it will not affect the underlying managed callback, so <xref:System.Runtime.InteropServices.GCHandle.Alloc%2A> is used to add a reference to the delegate, allowing relocation of the delegate, but preventing disposal. Using GCHandle instead of pin_ptr reduces fragmentation potential of the managed heap.

```cpp
// MarshalDelegate1.cpp
Expand Down