Domanda

Buongiorno, pomeriggio o sera,

Prefazione: il codice seguente non fa nulla di veramente utile.È solo a scopo illustrativo.

C'è qualcosa di sbagliato nell'allocazione e nell'utilizzo di un array "modalità sicura" all'interno di codice non sicuro?Ad esempio, dovrei scrivere il mio codice come

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;
    }
}

o dovrei invece scrivere un metodo separato e non sicuro che accetti solo puntatori e lunghezze come parametri e usarlo nella funzione principale?

Inoltre, esiste un modo per sostituire l'allocazione con

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

in modo da poter utilizzare Result come puntatore ed essere ancora in grado di restituire Result come uint[]?

Grazie mille.

È stato utile?

Soluzione

Non vedo nulla di sbagliato in questo, anche se se stai usando i puntatori per la velocità, probabilmente ha senso usare anche un puntatore in Result.Forse in questo modo:

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;
}

NON restituire nulla di ciò che stackalloc!Una volta che la funzione ritorna, l'area allocata nello stack viene riutilizzata, fornendo un puntatore non valido.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top