본문 바로가기

Programming/ASP .NET

C#에서 고정 크기 구조체 사용과 바이트 배열로 형 변환

public struct Test_Struct_t
{
    public byte var1;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public char[] str; // (1)
    //public char[] str; // (2)
}

public class AP_DB_Cmd_Box : AP_DB_Common
{
    // protected members    
    Test_Struct_t test_struct;
    int length;
    byte[] cmd_tmp;
    IntPtr cmd_ptr;
       

    public AP_DB_Cmd_Box() : base()
    {
        test_struct.str = new char[10]; // 꼭 해줘야한다. 안그럼 아래에서 에러
        test_struct.var1 = 1;      
        test_struct.str[0] = '0';
        test_struct.str[1] = '1';

        length = Marshal.SizeOf(test_struct); // (1) 인 경우 11, (2)인 경우 8
        cmd_ptr = Marshal.AllocHGlobal(length); // 포인터 생성
        cmd_tmp = new byte[length]; // 바이트 배열 생성
        Marshal.StructureToPtr(test_struct, cmd_ptr, true); // 구조체 -> 포인터
        Marshal.Copy(cmd_ptr, cmd_tmp, 0, length); // 포인터 -> 바이트 배열로 복사
        Marshal.FreeHGlobal(cmd_ptr); // 포인터 해제

    }