본문 바로가기
▶ 프로그래밍 [Programming]/▷ C# 언어 [C# Language]

[C# 언어] Object/Struct to Byte array, Byte array to Object/Struct 형변환

by (๑′ᴗ‵๑) 2023. 9. 17.
반응형

 

 

안녕하세요,

 

오늘은 byte array to object / structure 형변환과 byte array to object / structure 형변환에 대해 포스팅 해보도록 하겠습니다.

 

반응형

 

형변환 소스코드

 

 

using System.Runtime.InteropServices;

public class Converter

{

    /// <summary>

    /// Convert object to byte array

    /// </summary>

    /// <param name="arr">Object to convert</param>

    /// <returns>Converted byte array from the given object</returns>

    public static byte[] ObjectToByte(object obj)

    {

        int size = Marshal.SizeOf(obj);

        byte[] arr = new byte[size];

        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.StructureToPtr(obj, ptr, true);

        Marshal.Copy(ptr, arr, 0, size);

        Marshal.FreeHGlobal(ptr);

        return arr;

    }

   

    /// <summary>

    /// Convert byte array to object

    /// </summary>

    /// <param name="arr">Byte array to convert</param>

    /// <returns>Converted object from the given byte array</returns>

    public static T ByteToObject<T>(byte[] arr) where T : struct

    {

        int size = Marshal.SizeOf(typeof(T));

        if (size > arr.Length)

        {

            throw new Exception();

        }

        IntPtr ptr = Marshal.AllocHGlobal(size);

        Marshal.Copy(arr, 0, ptr, size);

        T obj = (T)Marshal.PtrToStructure(ptr, typeof(T));

        Marshal.FreeHGlobal(ptr);

        return obj;

    }

}

 

 

Structure to UInt64의 경우 1) structure to byte array, 2) byte arry to UInt64의 작업을 통해 형 변환이 가능합니다. 이와 같이 위 메소드를 이용해 다양한 타입의 형 변환을 할 수 있습니다.

 

 

감사합니다.

 

반응형

댓글