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[]?

非常感谢你。

4

1 回答 1

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!一旦函数返回,分配在堆栈上的区域被重用,给你一个无效的指针。

于 2011-03-23T08:08:26.933 回答