본문 바로가기

프로그램/유니티 스크립트 소스

[유니티 스크립트 소스] Struct ↔ Byte 배열

728x90
반응형

1. 네임스페이스

네임스페이스
using System;
using System.Runtime.InteropServices;

 

2. Byte 배열  Struct

메서드 : Byte 배열  Struct
public T ByteArrayToStruct<T>(byte[] buffer) where T : struct
{
    int size = Marshal.SizeOf(typeof(T));
    if (size > buffer.Length)
    {
        throw new Exception();
    }
               
    IntPtr ptr = Marshal.AllocHGlobal(size);
    Marshal.Copy(buffer, 0, ptr, size);
    T obj = (T)Marshal.PtrToStructure(ptr, typeof(T));
    Marshal.FreeHGlobal(ptr);
    return obj;
}

 

3. Struct → Byte 배열

메서드 : Struct → Byte 배열
public byte[] StructToByteArray(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;
}
728x90
반응형