Microsoft MVP성태의 닷넷 이야기
.NET Framework: 399. LayoutKind 옵션에 대해 [링크 복사], [링크+제목 복사],
조회: 22679
글쓴 사람
정성태 (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)
13718정성태8/27/20247442오류 유형: 921. Visual C++ - error C1083: Cannot open include file: 'float.h': No such file or directory [2]
13717정성태8/26/20247037VS.NET IDE: 192. Visual Studio 2022 - Windows XP / 2003용 C/C++ 프로젝트 빌드
13716정성태8/21/20246767C/C++: 167. Visual C++ - 윈도우 환경에서 _execv 동작 [1]
13715정성태8/19/20247386Linux: 78. 리눅스 C/C++ - 특정 버전의 glibc 빌드 (docker-glibc-builder)
13714정성태8/19/20246766닷넷: 2295. C# 12 - 기본 생성자(Primary constructors) (책 오타 수정) [3]
13713정성태8/16/20247494개발 환경 구성: 721. WSL 2에서의 Hyper-V Socket 연동
13712정성태8/14/20247229개발 환경 구성: 720. Synology NAS - docker 원격 제어를 위한 TCP 바인딩 추가
13711정성태8/13/20248076Linux: 77. C# / Linux - zombie process (defunct process) [1]파일 다운로드1
13710정성태8/8/20248008닷넷: 2294. C# 13 - (6) iterator 또는 비동기 메서드에서 ref와 unsafe 사용을 부분적으로 허용파일 다운로드1
13709정성태8/7/20247766닷넷: 2293. C# - safe/unsafe 문맥에 대한 C# 13의 (하위 호환을 깨는) 변화파일 다운로드1
13708정성태8/7/20247559개발 환경 구성: 719. ffmpeg / YoutubeExplode - mp4 동영상 파일로부터 Audio 파일 추출
13707정성태8/6/20247793닷넷: 2292. C# - 자식 프로세스의 출력이 4,096보다 많은 경우 Process.WaitForExit 호출 시 hang 현상파일 다운로드1
13706정성태8/5/20247899개발 환경 구성: 718. Hyper-V - 리눅스 VM에 새로운 디스크 추가
13705정성태8/4/20248170닷넷: 2291. C# 13 - (5) params 인자 타입으로 컬렉션 허용 [2]파일 다운로드1
13704정성태8/2/20248126닷넷: 2290. C# - 간이 dotnet-dump 프로그램 만들기파일 다운로드1
13703정성태8/1/20247451닷넷: 2289. "dotnet-dump ps" 명령어가 닷넷 프로세스를 찾는 방법
13702정성태7/31/20247861닷넷: 2288. Collection 식을 지원하는 사용자 정의 타입을 CollectionBuilder 특성으로 성능 보완파일 다운로드1
13701정성태7/30/20248131닷넷: 2287. C# 13 - (4) Indexer를 이용한 개체 초기화 구문에서 System.Index 연산자 허용파일 다운로드1
13700정성태7/29/20247759디버깅 기술: 200. DLL Export/Import의 Hint 의미
13699정성태7/27/20248251닷넷: 2286. C# 13 - (3) Monitor를 대체할 Lock 타입파일 다운로드1
13698정성태7/27/20248213닷넷: 2285. C# - async 메서드에서의 System.Threading.Lock 잠금 처리파일 다운로드1
13697정성태7/26/20247934닷넷: 2284. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/20247469오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/20247456닷넷: 2283. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/20247920닷넷: 2282. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/20247245개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
1  2  3  4  5  6  7  8  [9]  10  11  12  13  14  15  ...