Unsafe code to change length (by mutation!) of a String object?

此生再无相见时 提交于 2019-12-07 03:54:12

问题


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.



来源:https://stackoverflow.com/questions/8176585/unsafe-code-to-change-length-by-mutation-of-a-string-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!