tags:

views:

157

answers:

4
+9  Q: 

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

+6  A: 

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.

codekaizen
A: 

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.

Guffa
A: 

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

Chris Hutchinson
+1  A: 

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

egrunin