Unable to convert uint * to uint []

I have this code that does not 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 will not compile, but I seem to be at the point where I am too tired to think, and I need help to put me in the right direction. For some time I did not work with unsafe code, but I am sure that I need to make Array.Copy (or Buffer.BlockCopy ?) And return a copy of the array, however those do not accept the arguments I need. What am I forgetting?

Thanks.

+6
source share
3 answers

You work in the fixed context when working with the 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]; } } } } } 
+4
source

It may be simpler, but it 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 length is 32 fixed (uint* ptr = myUints) { for (int i = 0; i < value.Length; i++) ptr[i] = value[i]; } } } } 
+2
source

This only works with int , float , byte , char and double , but you can use Marshal.Copy() to move data from a fixed array to a managed array.

Example:

 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); } } } } 
0
source

Source: https://habr.com/ru/post/898121/