在C#不安全代码 [英] Unsafe code in C#

查看:109
本文介绍了在C#不安全代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是不安全的代码的局限性,在C#中?例如,我可以做几乎任意的指针类型转换和算术,好像我是用C或C ++?

What are the limitations of unsafe code, in C#? For example, can I do virtually arbitrary pointer casts and arithmetic as if I were using C or C++?

推荐答案

是的。的所有的赌注都关闭不安全时,在播放

Yes. All bets are off when unsafe is in play.

这是背后的想法不安全 - 即可核实的各类安全被删除,你可以从一个类型的指针转​​换为另一种类型的指针不运行时保持你的搬起石头砸自己的脚,如果​​你愿意的话 - 就像C或C ++

This is the idea behind "unsafe" - that the "safety" of verifiable types is removed, and you can cast from a pointer of one type to a pointer of another type without the runtime keeping you from shooting yourself in the foot, if you so desire - much like C or C++.

下面是使用不同的例子指针类型在C#中:

Here's an example of using different pointer types in C#:

fixed (Byte* dstBytes = &currentImage[0])
{
    var dstBuffer = (Int64*)dstBytes;
    const int blockCount = ImageSizeInBytes / sizeof(Int64);

    for (var j = 0; j < blockCount; j++)
    {
        dstBuffer[j] = srcBuffer[j];
    }
}

请注意数组的类型是字节] ,但之后,我收到了字节* 我可以将它转换为的Int64 * ,并在同一时间8字节工作。

Note the type of the array is Byte[], but after I get a Byte* I can cast it to Int64* and work with 8 bytes at a time.

这篇关于在C#不安全代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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