Unsafe code to change length (by mutation!) of a S

2019-04-28 13:51发布

问题:

As .NET doesn't use C style nulls to end a string how can I keep the allocated string but change the length of it by using unsafe code?

As I understand .NET using a 20 bytes header for every string, presumably this is where the length of the string is stored, is there anyway to directly modify this length? So .NET will keep the string in memory but when I call .Length it'll return the .Length I want.

if this is possible, also it would be interesting to hear all crazy possible side-effects of this

UPDATE

I'm trying accomplish this without using reflection.

回答1:

From Strings UNDOCUMENTED

public static unsafe void SetLength(string s, int length)
{
    fixed(char *p = s)
    {
        int *pi = (int *)p;
        if (length<0 || length > pi[-2])
            throw( new ArgumentOutOfRangeException("length") );
        pi[-1] = length;
        p[length] = '\0';
    }
}


回答2:

You can use Reflection to set the m_StringLength field.