본문 바로가기

Programming/C#

구조체 -> 바이트 배열, 바이트 배열 -> 구조체

통신 프로그램을 만들 때 프로토콜을 구조체로 잡고 바이트 배열로 쏘는 경우가 생기는데

아래와 같이 하면 된다.

// 구조체를 바이트 배열로 변환
public static int CvtStructToBin(object obj, out byte[] bin)
{
      bin = new byte[Marshal.SizeOf(obj)];

      unsafe
      {
          fixed (byte* fixed_buffer = bin)
          {
              Marshal.StructureToPtr(obj, (IntPtr)fixed_buffer, false);
          }
      }

      return bin.Length;

}

// 바이트 배열을 구조체로 변환

        public static int CvtBinToStruct(byte[] bin, object obj)
        {
            
            unsafe
            {
                fixed (byte* fixed_buffer = bin)
                {
                    Marshal.PtrToStructure((IntPtr)fixed_buffer, obj);
                }
            }

            return 0;
        }

'Programming > C#' 카테고리의 다른 글

C#에서 로그 함수 만들기  (0) 2010.03.05