2011-03-23 81 views
0

早上好,下午或晚上,安全索引里面不安全代码

前言:下面的代码什么也不做真正有用的。这只是为了说明的目的。

这有什么错分配和使用不安全的代码里的数组是“安全模式”?例如,我应该写我的代码作为

public static unsafe uint[] Test (uint[] firstParam, uint[] secondParam) 
{ 
    fixed (uint * first = firstParam, second = secondParam) 
    { 
     uint[] Result = new uint[firstParam.Length + secondParam.Length]; 

     for (int IndTmp = 0; IndTmp < firstParam.Length; Result[IndTmp] = *(first + IndTmp++)); 
     for (int IndTmp = 0; IndTmp < secondParam.Length; Result[IndTmp + firstParam.Length] = *(second + IndTmp++); 

     return Result; 
    } 
} 

或我应该代替写一个单独的,不安全的方法只接受指针和长度作为参数,并在主函数使用它?

此外,有没有什么办法可以用

uint * Result = stackalloc uint[firstParam.Length + secondParam.Length] 

更换分配,这样我可以使用Result为指针,并且仍然能够返回Result作为uint[]

非常感谢。

回答

2

我看没有错这样做,但如果你使用指针的速度,它可能是有意义的使用指针到Result也。也许是这样的:

public static unsafe uint[] Test (uint[] firstParam, uint[] secondParam) 
{ 
    uint[] Result = new uint[firstParam.Length + secondParam.Length]; 
    fixed (uint * first = firstParam, second = secondParam, res = Result) 
    { 
     for (int IndTmp = 0; IndTmp < firstParam.Length; IndTmp++) 
      *(res + IndTmp) = *(first + IndTmp); 
     res += firstParam.Length; 
     for (int IndTmp = 0; IndTmp < secondParam.Length; IndTmp++) 
      *(res + IndTmp) = *(second + IndTmp++); 
    } 
    return Result; 
} 

切勿任何回报你stackalloc!一旦函数返回时,在栈上分配的区域被重用,给你一个无效的指针。