0

I was wondering about how passing a String or a StringBuilder to a C function which output a string by parameter. I've found a great answer in

Calling unmanaged function from C#: should I pass StringBuilder or use unsafe code?

But I have a doubt. Anyone can explain to me why the garbage collector doesn't relocate the (managed) StringBuilder instance during imported function execution?

Community
  • 1
  • 1
Luca
  • 11,646
  • 11
  • 70
  • 125

1 Answers1

1

See Default Marshaling for Strings for details on how string and StringBuilder is marshaled when using COM and P/Invoke. It doesn't explicitly say why the usage pattern is safe, but does indicate that using string and StringBuilder for P/Invoke is supported and intended behaviour. I suspect that the marshalling system takes care of pinning the buffer for the duration of the external call, preventing the GC from relocating it.

SoftMemes
  • 5,602
  • 4
  • 32
  • 61