PInvoke stringbuilder vs string

  • Thread starter Thread starter Urban Andersson
  • Start date Start date
U

Urban Andersson

In all recomendations from Microsoft you read that you should use
StringBuilder instead of String when passing an In/Out parameter to a
external function. What is the benefits using the StringBuilder instead of
string. Both need to have the capacity to hold the string recieved the only
difference is that you recieve an exception when the buffer is to small in a
stringbuilder. When using the string you will not recieve an exception but
the unmaged code will overwrite the buffer if it is not of suffient size. Is
there any other difference between the two?
 
Urban,

String is designed to be immutable. For performance reasons, the
runtime will sometimes send a direct pointer to the string's internal
buffer when you pass the string to a P/Invoke function. If that
function modifies the string buffer, you break the immutability of the
string, which may have bad side effects.



Mattias
 
Native calls COULD crash the runtime and also have buffer overruns. You
still have the same risk as you do in unmanaged code when you start going
native.
 
Hi Mattias

Thansk for your answer. But even if the string is immutable in this scenario
it realy doesn't matter except i may be bad design. What confuses me is that
I get an exception when using StringBuilder and not string. Could it has
something to do with how the memory is allocated for the string? So it is so
that the stringbuilder is using allocation from the global heap. So that the
unmanagade code knows about the allocation size for the StringBuilder string
and throws an exception back to the framework. And that the string object is
allocated in the .net framework local heap and that heap is not known to the
managed code?

/Urban
 
Urban,
But even if the string is immutable in this scenario
it realy doesn't matter except i may be bad design.

It doesn't?

What confuses me is that
I get an exception when using StringBuilder and not string.

I don't know why you're seeing that. I guess it's possible that there
are some extra checks done for StringBuilders. But I don't see why it
matters. Surely you should avoid the buffer overflow (by, for example,
passing in the buffer size as a parameter) rather than expecting the
CLR to figure out something is wrong.



Mattias
 
Back
Top