Mike
Mike

Reputation: 1295

When is pinning required to avoid C# garbage collector moving an object?

When is pinning using the fixed() statement required? I see many examples, including this from Microsoft:

public class Win32API {
[DllImport("User32.Dll")]
public static extern void GetWindowText(int h, StringBuilder s, 
int nMaxCount);
}
public class Window {
   internal int h;        // Internal handle to Window.
   public String GetText() {
      StringBuilder sb = new StringBuilder(256);
      Win32API.GetWindowText(h, sb, sb.Capacity + 1);
   return sb.ToString();
   }
}

What prevents the garbage collector from moving the StringBuilder object during the GetWindowText() call, and why aren't they pinning sb with the fixed() statement?

Upvotes: 2

Views: 316

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564471

The marshalling system when you use Platform Invocation will prevent the object from being moved, but only during the method call's duration.

Pinning is required if the native side is going to save a reference to the object, and try to do "something" with it later. It is not required for a single call into a native method using P/Invoke.

Upvotes: 7

Related Questions