不安全code来改变一个String对象的长度(通过突变!)?突变、不安全、长度、对象

2023-09-04 02:42:22 作者:眸七

由于.NET没有用C风格的 s到结束的字符串我怎能分配的字符串,但使用不安全$ C $改变它的长度C吗?

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?

据我了解.NET使用的是20个字节的头,每串,presumably这就是字符串的长度存储,反正是有直接修改此长度是多少?因此.NET将保持在字符串中的内存,但是当我打电话 .Length 它会返回 .Length 我要。

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.

这是可能的,也是这将是有趣的,听到这一切的疯狂可能产生的副作用的

更新

我试图做到这一点,而无需使用反射。

I'm trying accomplish this without using reflection.

推荐答案

从字符串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';
    }
}
 
精彩推荐
图片推荐