Reputation: 11971
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?
Upvotes: 0
Views: 621
Reputation: 5702
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.
Upvotes: 1