Microsoft MVP성태의 닷넷 이야기
.NET Framework: 399. LayoutKind 옵션에 대해 [링크 복사], [링크+제목 복사],
조회: 22672
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

LayoutKind 옵션에 대해

재미있는 글이 하나 떴습니다. ^^

[제목] 객체의 메모리 레이아웃에 대하여
; http://www.csharpstudy.com/network/DevNote/Article/1009

위의 글에서 제가 의심이 되는 것은 다음의 문구입니다.

Sequential Layout은 Managed Memory에서 마샬링을 사용해 Unmanaged Memory로 옮길 때 각 필드의 순서가 Unmanaged Memory에서 유지되는 레이아웃이다. 위의 예제에서 MyStruct구조체는 [StructLayout(LayoutKind.Sequential)]을 사용하고 있는데, 이는 Managed 메모리 영역에서는 순서가 어떨지 모르지만, Unmanaged Memory로 옮겨질 때는 반드시 필드 순서대로 데이타가 옮겨진다는 것을 의미한다.


즉, 위의 글에 따라 LayoutKind 옵션을 정리하면 다음과 같은 식입니다.

Layout 관리 메모리 필드 순서 보장 비관리 메모리 필드 순서 보장
Auto X X
Sequential X O
Explicit O O

의심스러운 것은 Sequential인 경우 Managed에서는 다른 메모리 구조를 가지고 있다가 Unmanaged로 복사할 때 굳이 필드 정의 순서대로 변환하는 비효율적인 작업을 하느냐에 대한 것입니다.

위의 글을 보고 MSDN 도움말을 찾아봤는데요.

LayoutKind Enumeration
; https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind

Explicit 옵션에 대해서 다음과 같이 설명하고 있습니다.

The precise position of each member of an object in unmanaged memory is explicitly controlled, subject to the setting of the StructLayoutAttribute.Pack field. Each member must use the FieldOffsetAttribute to indicate the position of that field within the type.


위의 글에 보면, unmanaged에 대한 언급은 있지만 managed에 대한 언급은 없습니다. 이렇게 되면 확실하게 결론 내리기 위해 테스트를 통해서 한번 증명을 해봐야 될 것 같습니다.




예제는 다음과 같이 구성해 보았습니다.

using System;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    [StructLayout(LayoutKind.Sequential)]
    class A
    {
        byte b1 = 10;
        int i1 = 11;
        byte b2 = 12;
        int i2 = 13;
        byte b3 = 14;
        int i3 = 15;
        byte b4 = 16;
        int i4 = 17;
    }

    [StructLayout(LayoutKind.Sequential)]
    class B
    {
        byte b1 = 20;
        byte b2 = 21;
        byte b3 = 22;
        byte b4 = 23;
        int i1 = 24;
        int i2 = 25;
        int i3 = 26;
        int i4 = 27;
    }

    class Program
    {
        static void Main(string[] args)
        {
            A var1 = new A();
            B var2 = new B();

            int sizeofA = Marshal.SizeOf(var1);
            int sizeofB = Marshal.SizeOf(var2);

            Console.WriteLine("Check: " + var1.ToString() + ": " + sizeofA);
            Console.WriteLine("Check: " + var2.ToString() + ": " + sizeofB);
            Console.ReadLine();
        }
    }
}

ReadLine까지 실행한 다음 windbg를 이용해 managed 영역의 메모리를 검사해 보겠습니다.

0:006> .loadby sos clr


0:000> !name2ee *!ConsoleApplication1.A
Module:      720c1000
Assembly:    mscorlib.dll
--------------------------------------
Module:      00b72ed4
Assembly:    ConsoleApplication1.exe
Token:       02000002
MethodTable: 00b7386c
EEClass:     00b7136c
Name:        ConsoleApplication1.A

0:000> !dumpheap -mt 00b7386c
 Address       MT     Size
02702490 00b7386c       40     

Statistics:
      MT    Count    TotalSize Class Name
00b7386c        1           40 ConsoleApplication1.A
Total 1 objects


0:000> !dumpobj 02702490
Name:        ConsoleApplication1.A
MethodTable: 00b7386c
EEClass:     00b7136c
Size:        40(0x28) bytes
File:        d:\settings\Desktop\layout_explicit\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
724d36b4  4000001        4          System.Byte  1 instance       10 b1
724d3c50  4000002        8         System.Int32  1 instance       11 i1
724d36b4  4000003        c          System.Byte  1 instance       12 b2
724d3c50  4000004       10         System.Int32  1 instance       13 i2
724d36b4  4000005       14          System.Byte  1 instance       14 b3
724d3c50  4000006       18         System.Int32  1 instance       15 i3
724d36b4  4000007       1c          System.Byte  1 instance       16 b4
724d3c50  4000008       20         System.Int32  1 instance       17 i4

보시는 바와 같이 Sequential인 경우에도 managed 메모리에서의 필드 순서가 보장되고 있습니다. B 클래스도 마저 확인을 해볼까요?

0:000> !name2ee *!ConsoleApplication1.B
Module:      720c1000
Assembly:    mscorlib.dll
--------------------------------------
Module:      00b72ed4
Assembly:    ConsoleApplication1.exe
Token:       02000003
MethodTable: 00b73928
EEClass:     00b71494
Name:        ConsoleApplication1.B

0:000> !dumpheap -mt 00b73928
 Address       MT     Size
027024b8 00b73928       28     

Statistics:
      MT    Count    TotalSize Class Name
00b73928        1           28 ConsoleApplication1.B
Total 1 objects

0:000> !dumpobj 027024b8
Name:        ConsoleApplication1.B
MethodTable: 00b73928
EEClass:     00b71494
Size:        28(0x1c) bytes
File:        d:\settings\Desktop\layout_explicit\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
724d36b4  4000009        4          System.Byte  1 instance       20 b1
724d36b4  400000a        5          System.Byte  1 instance       21 b2
724d36b4  400000b        6          System.Byte  1 instance       22 b3
724d36b4  400000c        7          System.Byte  1 instance       23 b4
724d3c50  400000d        8         System.Int32  1 instance       24 i1
724d3c50  400000e        c         System.Int32  1 instance       25 i2
724d3c50  400000f       10         System.Int32  1 instance       26 i3
724d3c50  4000010       14         System.Int32  1 instance       27 i4

역시 순서가 지켜지고 있습니다. 게다가 2가지 Offset 값에 따라 크기를 계산해 보면 A 클래스의 인스턴스는 32바이트, B 클래스의 인스턴스는 20바이트로 Console.WriteLine으로 출력했던 sizeofA, sizeofB 변수의 값과 동일합니다. 결과적으로 Sequential인 경우에도 Managed와 Unmanaged의 필드 배치가 동일하다는 것을 유추할 수 있습니다.

실제로 순서가 달라진다는 것을 확인하기 위해 A 클래스를 Auto로 바꾸면 다음과 같이 Offset 값이 뒤죽박죽으로 나오는 것을 볼 수 있습니다.

0:000> !dumpobj 023f2490 
Name:        ConsoleApplication1.A
MethodTable: 0085386c
EEClass:     0085136c
Size:        28(0x1c) bytes
File:        d:\settings\Desktop\layout_explicit\ConsoleApplication1\ConsoleApplication1\bin\Debug\ConsoleApplication1.exe
Fields:
      MT    Field   Offset                 Type VT     Attr    Value Name
724d36b4  4000001       14          System.Byte  1 instance       10 b1
724d3c50  4000002        4         System.Int32  1 instance       11 i1
724d36b4  4000003       15          System.Byte  1 instance       12 b2
724d3c50  4000004        8         System.Int32  1 instance       13 i2
724d36b4  4000005       16          System.Byte  1 instance       14 b3
724d3c50  4000006        c         System.Int32  1 instance       15 i3
724d36b4  4000007       17          System.Byte  1 instance       16 b4
724d3c50  4000008       10         System.Int32  1 instance       17 i4

테스트에 따른 결론을 말하면, Sequential은 순서가 보장되지만 Offset 값은 CLR에 의해 고정됩니다. 반면 Explicit은 Sequential의 기능과 함께 Offset 값을 개발자가 제어할 수 있는 기능을 부가하는 차이점이 있을 뿐입니다.

혹시... 제가 잘못 이해하고 있거나 테스트에 뭔가 잘못된 점이 있을까요? ^^






[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2013-12-27 09시50분
[Alex Lee] Sequential은 Managed Heap에서 "항상" 순서를 보장하는 것은 아닙니다.

[StructLayout(LayoutKind.Sequential, Pack = 1)]
class MyClass
{
    public int i;
    public string s;
    public double d;
    public byte b;
}

!do 0x0239237c
Name: ConsoleApplication2.Program+MyClass
MethodTable: 0015384c
EEClass: 0015130c
Size: 28(0x1c) bytes
Fields:
      MT Field Offset Type VT Attr Value Name
7138c770 4000001 10 System.Int32 1 instance 2 i
7138afb0 4000002 c System.String 0 instance 0239236c s
713872ec 4000003 4 System.Double 1 instance 5.000000 d
7138c22c 4000004 14 System.Byte 1 instance 1 b
[guest]
2013-12-28 05시46분
덧글 감사합니다. Alex 님 ^^ 이번에도 또 한번 배웠습니다. 글 수정해서 다시 쓰겠습니다. ^^
정성태

1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13793정성태10/28/20245149C/C++: 183. C++ - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법
13792정성태10/27/20244633Linux: 99. Linux - 프로세스의 실행 파일 경로 확인
13791정성태10/27/20244901Windows: 267. Win32 API의 A(ANSI) 버전은 DBCS를 사용할까요?파일 다운로드1
13790정성태10/27/20244621Linux: 98. Ubuntu 22.04 - 리눅스 커널 빌드 및 업그레이드
13789정성태10/27/20244914Linux: 97. menuconfig에 CONFIG_DEBUG_INFO_BTF, CONFIG_DEBUG_INFO_BTF_MODULES 옵션이 없는 경우
13788정성태10/26/20244459Linux: 96. eBPF (bpf2go) - fentry, fexit를 이용한 트레이스
13787정성태10/26/20244973개발 환경 구성: 730. github - Linux 커널 repo를 윈도우 환경에서 git clone하는 방법 [1]
13786정성태10/26/20245218Windows: 266. Windows - 대소문자 구분이 가능한 파일 시스템
13785정성태10/23/20244985C/C++: 182. 윈도우가 운영하는 2개의 Code Page파일 다운로드1
13784정성태10/23/20245248Linux: 95. eBPF - kprobe를 이용한 트레이스
13783정성태10/23/20244860Linux: 94. eBPF - vmlinux.h 헤더 포함하는 방법 (bpf2go에서 사용)
13782정성태10/23/20244621Linux: 93. Ubuntu 22.04 - 커널 이미지로부터 커널 함수 역어셈블
13781정성태10/22/20244801오류 유형: 930. WSL + eBPF: modprobe: FATAL: Module kheaders not found in directory
13780정성태10/22/20245550Linux: 92. WSL 2 - 커널 이미지로부터 커널 함수 역어셈블
13779정성태10/22/20244845개발 환경 구성: 729. WSL 2 - Mariner VM 커널 이미지 업데이트 방법
13778정성태10/21/20245671C/C++: 181. C/C++ - 소스코드 파일의 인코딩, 바이너리 모듈 상태의 인코딩
13777정성태10/20/20244953Windows: 265. Win32 API의 W(유니코드) 버전은 UCS-2일까요? UTF-16 인코딩일까요?
13776정성태10/19/20245269C/C++: 180. C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)파일 다운로드1
13775정성태10/19/20245492개발 환경 구성: 728. 윈도우 환경의 개발자를 위한 UTF-8 환경 설정
13774정성태10/18/20245196Linux: 91. Container 환경에서 출력하는 eBPF bpf_get_current_pid_tgid의 pid가 존재하지 않는 이유
13773정성태10/18/20244883Linux: 90. pid 네임스페이스 구성으로 본 WSL 2 + docker-desktop
13772정성태10/17/20245160Linux: 89. pid 네임스페이스 구성으로 본 WSL 2 배포본의 계층 관계
13771정성태10/17/20245066Linux: 88. WSL 2 리눅스 배포본 내에서의 pid 네임스페이스 구성
13770정성태10/17/20245337Linux: 87. ps + grep 조합에서 grep 명령어를 사용한 프로세스를 출력에서 제거하는 방법
13769정성태10/15/20246114Linux: 86. Golang + bpf2go를 사용한 eBPF 기본 예제파일 다운로드1
13768정성태10/15/20245396C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...