0

I have a class that contains two List of the same size that I need to convert to byte[] and copy them to another array.

Actually I use this code:

var lenght = MyObject.firstList[i].Count;
for (var i = 0; i < MyObject.firstList.Count; i++)
{
      BitConverter.GetBytes(MyObject.firstList[i]).CopyTo(bytes, i * sizeof(float));
      BitConverter.GetBytes(MyObject.secondList[i]).CopyTo(bytes, i * sizeof(float) + lenght * sizeof(float));
}

The problem of this code is that it always allocates a lot of memory causing the ** GC ** to intervene.

How can I optimize the code without making excessive memory allocations. Is there an optimal solution using unsafe or IntPtr or Span?

I tried to use this solution but the error appears

System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory

PREMISE:

  • I cant substitute List with a float[]
NickMan
  • 23
  • 4
  • Where in your code do you use List? Your code example also does not make sense as-is, as it is not valid C#. The condition in the for loop says `class.firstList.Lenght` is being an integer field/property, but then in the loop body you use an indexer on `class.firstList.Lenght` as if it were some indexable collection or something. And then `Lenght`, despite its misspelling strongly suggests you are using arrays, and not List. How can we help with your quite specific problem if the code you present to us doesn't even make sense...? –  Sep 28 '22 at 11:22
  • i just changed code. Can you understand now? – NickMan Sep 28 '22 at 13:37

1 Answers1

0

Just use Buffer.BlockCopy, as shown in the accepted answer to the question you refereed to.

Buffer.BlockCopy(myFloatArray, 0, myByteArray, 0 , myFloatArray.Length * sizeof(float));

There is also Marshal.Copy for copying from/to pointers.

In newer .Net versions there is also Span<T> that can be used as a kind of safe pointer to data, that allow casting of types.

JonasH
  • 28,608
  • 2
  • 10
  • 23