Microsoft MVP성태의 닷넷 이야기
.NET Framework: 399. LayoutKind 옵션에 대해 [링크 복사], [링크+제목 복사],
조회: 22756
글쓴 사람
정성태 (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 님 ^^ 이번에도 또 한번 배웠습니다. 글 수정해서 다시 쓰겠습니다. ^^
정성태

... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12740정성태7/29/202114631오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/202115014오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/202115963오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/202115070오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/202115352오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/202115195.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202132018스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202119937.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/202113354오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/202115383개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/202116831개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/202115291.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/202115331.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/202116505.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/202116279VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/202114761오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/202117681개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/202114532오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/202114306오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/202115479오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/202114753Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/202113928오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/202113933개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/202114120Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
12716정성태7/17/202115258개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법파일 다운로드1
12715정성태7/17/202122442오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...