Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# multiple arrays with the same memory

Is it possible in C# to have multiple arrays at the same memory location with the arrays having different types?
I have a large float array, and I need to convert it to a byte array in as short a time as possible.
My Idea was to have a byte array that points to the beginning of the float array, so that if I change the float array the byte array automatically changes as well, but I have not yet found a solution to do so.
Is that even possible in C# or do I have to find another way?

I need the byte array to be an actual array of type "byte[]", because I have to call a function in a library I have no access to.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can’t do that with actual arrays (at least of different element sizes in memory) – but if you’re happy to use that with Span<T> instead, then MemoryMarshal could be what you’re looking for. (And you can still use an array as the underlying storage.)

For example:

using System.Runtime.InteropServices;

Span<float> floats = new float[3];
Span<byte> bytes = MemoryMarshal.AsBytes(floats);

Console.WriteLine(bytes[0]); // 0
floats[0] = 1.234f;
Console.WriteLine(bytes[0]); // 182
bytes[0] = 200;
Console.WriteLine(floats[0]); // 1.2340021

Or to go in the opposite direction, keeping a byte[] variable but using a Span<float> as a sort of float-oriented view over the byte array:

using System.Runtime.InteropServices;

byte[] bytes = new byte[100];
Span<float> floats = MemoryMarshal.Cast<byte, float>(bytes);

Console.WriteLine(bytes[0]); // 0
floats[0] = 1.234f;
Console.WriteLine(bytes[0]); // 182
bytes[0] = 200;
Console.WriteLine(floats[0]); // 1.2340021
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading