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返すことができるようにResultuint[]

どうもありがとうございました。

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 に答える