Question

Good morning, afternoon or night,

Foreword: The code below does nothing really useful. It is just for explanation purposes.

Is there anything wrong with allocating and using an array "the safe mode" inside unsafe code? For example, should I write my code as

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

or should I instead write a separate, unsafe method accepting only pointers and lengths as parameters and use it in the main function?

Also, is there any way I can replace the allocation with

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

so that I can use Result as a pointer and still be able to return Result as an uint[]?

Thank you very much.

Was it helpful?

Solution

I see nothing wrong with doing that, although if you're using pointers for speed, it probably makes sense to use a pointer into Result also. Maybe like this:

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

DO NOT return anything you stackalloc! Once the function returns, the area allocated on the stack is reused, giving you an invalid pointer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top