Jump to content
  • Advertisement
rogerdv

C# Decomposing fixed byte[] in elements

Recommended Posts

Advertisement

The techniques I posted in the last thread work bidirectionally.

You can convert the fixed byte array to an IntPtr for use with Marshal with: new IntPtr(fixedArray);

using System;
using System.Runtime.InteropServices;

namespace ConsoleApp1
{
    class Program
    {
        static unsafe void Main(string[] args)
        {
            var buffer = new MyBuffer();

            buffer.fixedBuffer[3] = 1;
            buffer.fixedBuffer[4] = 0xC8;

            // section of the array that will be used now contains:
            // 00 00 00 01 C8 00 00 00
            // ^^^^^^^^^^^ ^^^^^^^^^^^
            // Foo         Bar
            // Little Endian will be used on Little Endian computers (the majority of them)
            // outputs will be:
            // Foo = 0x01000000 (16777216)
            // Bar = 0x000000C8 (2.802598E-43)

            var blarg = Marshal.PtrToStructure<Blarg>(new IntPtr(buffer.fixedBuffer));

            Console.WriteLine(blarg.Foo);
            Console.WriteLine(blarg.Bar);
              
            // To put values back in:
            blarg.Foo = 1;
            blarg.Bar = 1;

            Marshal.StructureToPtr(blarg, new IntPtr(buffer.fixedBuffer), false);

            for (int i=0; i<8; ++i)
            {
                Console.Write($"{buffer.fixedBuffer[i]:X2} ");
            }
            Console.WriteLine();
        }
    }

    [StructLayout(LayoutKind.Sequential)]
    struct Blarg
    {
        public int Foo;
        public float Bar;
    }

    internal unsafe struct MyBuffer
    {
        public fixed byte fixedBuffer[128];
    }
}

If you want to just convert the fixed byte[] to a normal byte[] you can copy the entire thing to a managed array using Marshal.Copy and then use normal C# byte[] techniques like MemoryStream, BinaryReader, StreamReader, BitConverter, etc.

Edited by Nypyren

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!