What is the correct way to set StringBuilder.Capacity when using P / Invoke?

If StringBuilder.Capacitythe maximum number of .NET characters is set, regardless of null termination, or should be set higher to reserve space for the null terminator when using P / Invoke.

The natural reaction is that it should be set one level higher, but it seems that P / Invoke should automatically compensate. In fact, it is actually registered here: http://msdn.microsoft.com/en-US/library/s9ts558h(v=VS.100).aspx

The reason for this question is that most of the examples are not fully consistent with the above documentation. Almost always, they are encoded:

StringBuilder sb = new StringBuilder(dotNetChars + 1);
SomeWindowsAPI(sb, sb.Capacity);

Instead:

StringBuilder sb = new StringBuilder(dotNetChars);
SomeWindowsAPI(sb, sb.Capacity + 1);

( , API- -. , API , GetFullPathName: http://msdn.microsoft.com/en-us/library/aa364963(v=VS.85).aspx)

sb.Capacity API, -, , . , +1.

. , , , sb.Capacity + 1, MSDN.

, , , , .

+5
3

, , , , , , , .

MSDN , Capacity StringBuilder . Default Marshaling for Strings:

[...]

, StringBuilder . A StringBuilder , StringBuilder. . , StringBuilder N, (N + 1) . +1 , , StringBuilder .

[...]

, , , .

+2

StringBuilder :

m_ChunkChars = new char[capacity];

m_ChunkLength StringBuilder. , .

, + 1 .

0

, . - , , , " + 1" . , , , " " + 1. , , . , , , , , .

0
source

All Articles