views:

92

answers:

1

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

http://stackoverflow.com/questions/1687558/calling-unmanaged-function-from-c-should-i-pass-stringbuilder-or-use-unsafe-cod

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?

+1  A: 

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.

Freed