在 struct [] 中使用不安全的 char* 提取 char 值时出现问题

having issues when extracting char values, using unsafe char* in a struct []

在这段代码中,我试图模拟一个填充结构数组的任务, ...获得尽可能多的吞吐量是不安全的。

问题是我在调用函数并对结果进行迭代时 显示不同的字符,但在GetSomeTs()范围内没问题。

所以就在 return 之前,我测试了其中一个元素,它打印了正确的值。

这是测试结构。

public unsafe struct T1
{
    public char* block = stackalloc char[5];<--will not compile so the process will be done within a local variable inside a method
}

public unsafe struct T1
{
    public char* block;
}

    static unsafe T1[] GetSomeTs(int ArrSz)
    {
        char[] SomeValChars = { 'a', 'b', 'c', 'd', 'e' };
        T1[] RtT1Arr = new T1[ArrSz];

        for (int i = 0; i < RtT1Arr.Length; i++)
        {
            char* tmpCap = stackalloc char[5];

            for (int l = 0; l < 5; l++)
            {
                SomeValChars[4] = i.ToString()[0];
                tmpCap[l] = SomeValChars[l]; 
            }


            RtT1Arr[i].block = tmpCap;//try 1
            //arr[i].block = &tmpCap[0];//try 2
        }
           // here its fine
        Console.WriteLine("{0}", new string(RtT1Arr[1].block)); 
        return RtT1Arr;
    }

但在其他任何地方使用它都会打印垃圾。

void Main()
{
     T1[] tstT1 = GetSomeTs(10);

        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("{0}", new string(tstT1[i].block));//,0,5, Encoding.Default));
        }
}

当您使用 stackalloc 分配内存时,该内存只存在于您分配它的函数 returns 之前。您正在返回一个指向不再允许访问的内存的指针。

很难推荐修复,因为不清楚您想要实现什么。也许,您应该只使用托管 char[].

Encoding.Default.GetBytes 速度很慢,所以这很可能是您的热点,其余的就不那么重要了。 i.ToString() 也很慢并且会产生垃圾。如果您追求 perf,那么请停止创建不需要的对象,例如 SomeValChars。创建一次并重复使用。