Microsoft MVP성태의 닷넷 이야기
.NET Framework: 399. LayoutKind 옵션에 대해 [링크 복사], [링크+제목 복사],
조회: 16383
글쓴 사람
정성태 (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)
13539정성태1/26/20242372개발 환경 구성: 703. Visual Studio - launchSettings.json을 이용한 HTTP/HTTPS 포트 바인딩
13538정성태1/25/20242426닷넷: 2211. C# - NonGC(FOH) 영역에 .NET 개체를 생성파일 다운로드1
13537정성태1/24/20242527닷넷: 2210. C# - Native 메모리에 .NET 개체를 생성파일 다운로드1
13536정성태1/23/20242600닷넷: 2209. .NET 8 - NonGC Heap / FOH (Frozen Object Heap) [1]
13535정성태1/22/20242471닷넷: 2208. C# - GCHandle 구조체의 메모리 분석
13534정성태1/21/20242260닷넷: 2207. C# - SQL Server DB를 bacpac으로 Export/Import파일 다운로드1
13533정성태1/18/20242484닷넷: 2206. C# - TCP KeepAlive의 서버 측 구현파일 다운로드1
13532정성태1/17/20242366닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242275닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242209닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20242088닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242231Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242156오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242242닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242209오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242296오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20242098오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242241닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242302닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20242070오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20242128닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242383닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242218스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242339닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242616닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242296개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...