Microsoft MVP성태의 닷넷 이야기
.NET Framework: 399. LayoutKind 옵션에 대해 [링크 복사], [링크+제목 복사]
조회: 16307
글쓴 사람
정성태 (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)
13599정성태4/17/2024251닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024265닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024332닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024643닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024771닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024977닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241041닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241201C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241162닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241138닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241147오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241290Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241092Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241148Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241221Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241626닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241864닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...