简体   繁体   English

安全索引不安全代码

[英]Safe Indexing Inside Unsafe Code

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[] ? 这样我可以使用Result作为指针,仍然可以将Result作为uint[]返回?

Thank you very much. 非常感谢你。

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. 我认为这样做并没有错,虽然如果你使用指针来提高速度,那么使用指针进入Result也是有意义的。 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 ! 请勿返回任何stackalloc Once the function returns, the area allocated on the stack is reused, giving you an invalid pointer. 函数返回后,堆栈上分配的区域将被重用,从而为您提供无效指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM