不安全的方法来获取指针字节数组 [英] Unsafe method to get pointer to byte array

查看:125
本文介绍了不安全的方法来获取指针字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是这样的行为将在C#中是有效的。



 公共类MyClass的
{
私人字节[ ]数据;
公共MyClass的()
{
this.data =新的字节[1024];
}
公共不安全字节*的getData()
{
字节*结果= NULL;
固定(字节* dataPtr =数据)
{
结果= dataPtr;
}
返回结果;
}
}


解决方案

如果你要关闭安全系统和你有责任确保该程序的存储安全性即可。一旦你这样做,您需要安全地做一切,而不需要安全系统帮助您。这就是不安全的意思



由于C#规范明确说:




只能使用固定语句来获得一个可移动的变量的地址,并且该地址只对固定语句的持续时间保持有效。




您在获得移动变量的地址,然后固定语句的时间后使用它,所以地址不再的有效的。因此,你被要求严格的这样做正是你在做什么的。



您应该不会,直到你有什么必须遵循的规则是彻底和深刻的理解写任何不安全代码。通过阅读所有的规范第18章的开始。


is this behaviour will be valid in C#

public class MyClass
{
    private byte[] data;
    public MyClass()
    {
        this.data = new byte[1024];
    }
    public unsafe byte* getData()
    {
        byte* result = null;
        fixed (byte* dataPtr = data)
        {
            result = dataPtr;
        }
        return result;
    }
}

解决方案

If you are going to turn off the safety system then you are responsible for ensuring the memory safety of the program. As soon as you do, you are required to do everything safely without the safety system helping you. That's what "unsafe" means.

As the C# specification clearly says:

the address of a moveable variable can only be obtained using a fixed statement, and that address remains valid only for the duration of that fixed statement.

You are obtaining the address of a moveable variable and then using it after the duration of the fixed statement, so the address is no longer valid. You are therefore specifically required to not do precisely what you are doing.

You should not write any unsafe code until you have a thorough and deep understanding of what the rules you must follow are. Start by reading all of chapter 18 of the specification.

这篇关于不安全的方法来获取指针字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆