且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C#不安全代码

更新时间:2022-04-13 03:32:55

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

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.