Search code examples
c#unsafe

Unsafe code in 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++?


Solution

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

    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++.

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

    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.