无法将uint*转换为uint[]。

7

我有这段代码无法编译:

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

现在,我知道为什么代码无法编译,但显然我已经太累了,需要一些帮助来指导我。我已经有一段时间没有使用不安全的代码了,但我相信我需要进行Array.Copy(或Buffer.BlockCopy?)并返回数组的副本,然而这些函数不接受我所需的参数。我忘了什么?
谢谢。
3个回答

5

当使用固定缓冲区时,您必须在固定的上下文中工作:

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

啊!我就知道它会是一些让人尴尬简单的东西。谢谢! - Christopher Currens

2
也许有更简单的解决方案,但是这个方法有效:
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];
            }
        }
    }
}

0

这个适用于 int, float, byte, chardouble 类型的数据,但你可以使用 Marshal.Copy() 将数据从固定数组移动到托管数组。

例子:

class Program
{
    static void Main(string[] args)
    {
        MyStruct s = new MyStruct();

        s.MyUints = new int[] { 
            1, 2, 3, 4, 5, 6, 7, 8, 
            9, 10, 11, 12, 13, 14, 15, 16, 
            1, 2, 3, 4, 5, 6, 7, 8, 
            9, 10, 11, 12, 13, 14, 15, 16 };

        int[] chk = s.MyUints;
        // chk containts the proper values
    }
}

public unsafe struct MyStruct
{
    public const int Count = 32; //array size const
    fixed int myUints[Count];

    public int[] MyUints
    {
        get
        {
            int[] res = new int[Count];
            fixed (int* ptr = myUints)
            {
                Marshal.Copy(new IntPtr(ptr), res, 0, Count);
            }
            return res;
        }
        set
        {
            fixed (int* ptr = myUints)
            {
                Marshal.Copy(value, 0, new IntPtr(ptr), Count);
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接