Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert uint* to uint[]

I have this code which doesn't compile:

public struct MyStruct
{
    private fixed uint myUints[32];
    public uint[] MyUints
    {
        get
        {
            return this.myUints;
        }
        set
        {
            this.myUints = value;
        }
    }
}

Now, I know why the code won't compile, but I'm apparently at the point where I'm too tired to think, and need some help to put me in the right direction. I haven't worked with unsafe code in a while, but I'm pretty sure I need to do an Array.Copy (or Buffer.BlockCopy?) and return a copy of the array, however those don't take the arguments I need. What am I forgetting about?

Thanks.

like image 901
Christopher Currens Avatar asked Sep 27 '11 03:09

Christopher Currens


2 Answers

You have to work in a fixed context when working with a fixed buffer:

public unsafe struct MyStruct {
    private fixed uint myUints[32];
    public uint[] MyUints {
        get {
            uint[] array = new uint[32];
            fixed (uint* p = myUints) {
                for (int i = 0; i < 32; i++) {
                    array[i] = p[i];
                }
            }
            return array;
        }
        set {
            fixed (uint* p = myUints) {
                for (int i = 0; i < 32; i++) {
                    p[i] = value[i];
                }
            }
        }
    }
}
like image 109
jason Avatar answered Sep 28 '22 05:09

jason


There may be an easier solution, but this works:

public unsafe struct MyStruct
{
    private fixed uint myUints[32];
    public uint[] MyUints
    {
        get
        {
            fixed (uint* ptr = myUints)
            {
                uint[] result = new uint[32];
                for (int i = 0; i < result.Length; i++)
                    result[i] = ptr[i];
                return result;
            }
        }
        set
        {
            // TODO: make sure value's length is 32
            fixed (uint* ptr = myUints)
            {
                for (int i = 0; i < value.Length; i++)
                    ptr[i] = value[i];
            }
        }
    }
}
like image 37
svick Avatar answered Sep 28 '22 05:09

svick