Unsafe code in C#

戏子无情 提交于 2019-11-30 11:39:26
codekaizen

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.

Yes, that's all possible. Here's the Unsafe Code Tutorial from MSDN.

To all those saying how using this is a horrible idea: yes, but it's there for a reason. I had to use this (for the first time) just recently, getting webcam data via a third-party API that returned Byte *.

Yes, you can make a pointer point anywhere you like.

However, as your program is running in a virtual address space, you can only access the memory that actually exist in that space, i.e. you can't access any other processes, and you can't access memory that hasn't been allocated.

You can consult the following page for more information:

http://msdn.microsoft.com/en-us/library/y31yhkeb.aspx

Unsafe code provides the ability to declare pointers for virtually any primitive variable (fundamental types); you're allowed to cast between pointer types. Pointer arithmetic is based on the storage size of the pointer type, so applying post-increment or post-decrement to a pointer will increase the address by sizeof(type).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!