开发者

Unsafe code and fixed statements with StringBuilder

I was wondering about how passing a String or a StringBuilder to a C function which output a string by parameter. I've f开发者_开发百科ound 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜