Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요?

지난 글에 설명한 Unsafe.AsPointer가,

C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기
; https://www.sysnet.pe.kr/2/0/13017

과연 해당 메모리를 pinning 시킬까요? 사실 저도 지난 글을 쓸 때 그 점을 염두에 두지 않았습니다. (좋은 질문을 해주셔서 이렇게 보완하는 글을 쓰게 되었습니다. ^^)

일단, 얼핏 보고... 판단할 수는 있습니다. fixed의 경우 block이 정해져 있기 때문에 pinning 시킨 메모리의 유효 범위가 결정됩니다. 하지만, Unsafe.AsPointer의 경우에는 해당 포인터가 pinning 되었다면 언제 pinning을 해제해야 할지에 대한 표시가 없습니다. 그런 의미에서, 아마도 Unsafe.AsPointer는 pinning 시키지 않았을 거라고 짐작할 수 있습니다.

간단한 예제를 통해 눈으로도 확인할 수 있습니다.

using System.Runtime.CompilerServices;

class Program
{
    public int value = 27;

    static unsafe void Main(string[] args)
    {
        AllocGarbage();

        Program pg = new Program();
        Program pg2 = new Program();

        WriteAddress("Unsafe.AsPointer", pg);
        WriteAddress("fixed", pg2);

        void* ptr2 = Unsafe.AsPointer(ref pg.value);
        fixed (void* ptr = &pg2.value)
        {
            GC.Collect();
            GC.Collect();
        }

        Console.WriteLine("... gced ...");

        WriteAddress("Unsafe.AsPointer", pg);
        WriteAddress("fixed", pg2);
    }

    private static unsafe void WriteAddress(string title, Program pg)
    {
        void* ptr = Unsafe.AsPointer(ref pg.value);
        IntPtr p = new IntPtr(ptr);

        Console.Write($"{title} ");
        Console.WriteLine(p.ToString("x"));
    }

    private static void AllocGarbage()
    {
        for (int i = 0; i < 10000; i++)
        {
            int[] values = new int[1024];
        }
    }
}

위와 같이 GC가 되었을 경우 메모리가 이동하도록 코드를 구성한 다음, Unsafe.AsPointer의 대상이었던 pg 인스턴스와, fixed의 대상이었던 pg2 인스턴스의 메모리 포인터를 비교해 보면 됩니다.

실행해 보면, 대충 이런 출력 결과를 얻을 수 있습니다.

Unsafe.AsPointer: 2a0a4da7098
fixed: 2a0a4da70b0
... gced ...
Unsafe.AsPointer: 2a0a4da45e8
fixed: 2a0a4da70b0

보시면, Unsafe.AsPointer로 처리한 pg 인스턴스는 이동이 되어 메모리 위치가 바뀐 반면, fixed의 경우에는 바뀌지 않았습니다.




그런데, 갑자기 궁금해졌습니다. pinning 여부가 도대체 어떻게 결정되는 걸까요?

우선, Unsafe.AsPointer의 소스 코드는 이렇습니다.

Unsafe.il
; https://github.com/DotNetCross/Memory.Unsafe/blob/master/src/DotNetCross.Memory.Unsafe/Unsafe.il

.method public hidebysig static void* AsPointer<T>(!!T& 'value') cil managed aggressiveinlining
{
    .custom instance void System.Runtime.Versioning.NonVersionableAttribute::.ctor() = ( 01 00 00 00 )
    .maxstack 1
    ldarg.0
    conv.u
    ret
} // end of method Unsafe::AsPointer

여기서 재미있는 건, 사실 fixed의 IL 코드도 저것과 완전히 동일하다는 점입니다. 가령 다음과 같이 코딩을 한 후,

class Program
{
    public int value = 27;

    static unsafe void Main(string[] args)
    {
        Program pg = new Program();

        fixed (void* ptr = &pg.value)
        {
        }
    }
}

IL 코드로 보면,

.maxstack 1
.entrypoint
.locals init (
    [0] class Program pg,
    [1] void* ptr,
    [2] int32& pinned
)

/* 0x000002A0 00           */ IL_0000: nop  // Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.
/* 0x000002A1 7306000006   */ IL_0001: newobj    instance void Program::.ctor() // Creates a new object or a new instance of a value type, pushing an object reference (type O) onto the evaluation stack.
/* 0x000002A6 0A           */ IL_0006: stloc.0  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 0.
/* 0x000002A7 06           */ IL_0007: ldloc.0  // Loads the local variable at index 0 onto the evaluation stack.
/* 0x000002A8 7C03000004   */ IL_0008: ldflda    int32 Program::'value' // Finds the address of a field in the object whose reference is currently on the evaluation stack.
/* 0x000002AD 0C           */ IL_000D: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

/* 0x000002AE 08           */ IL_000E: ldloc.2  // Loads the local variable at index 2 onto the evaluation stack.
/* 0x000002AF E0           */ IL_000F: conv.u   // Converts the value on top of the evaluation stack to unsigned native int, and extends it to native int.
/* 0x000002B0 0B           */ IL_0010: stloc.1  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 1.

/* 0x000002B1 00           */ IL_0011: nop  // Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.
/* 0x000002B2 00           */ IL_0012: nop  // Fills space if opcodes are patched. No meaningful operation is performed although a processing cycle can be consumed.
/* 0x000002B3 16           */ IL_0013: ldc.i4.0 // Pushes the integer value of 0 onto the evaluation stack as an int32.
/* 0x000002B4 E0           */ IL_0014: conv.u   // Converts the value on top of the evaluation stack to unsigned native int, and extends it to native int.
/* 0x000002B5 0C           */ IL_0015: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.
/* 0x000002B6 2A           */ IL_0016: ret  // Returns from the current method, pushing a return value (if present) from the callee's evaluation stack onto the caller's evaluation stack.

단순히, conv.u 연산을 해 void* 변수에 넣는 것이 전부입니다. 그런데, 어떻게 저것이 fixed 블록에 의해 pinning 되는 걸까요? 그 이유는, 로컬 변수 중 pinned 특성이 지정된 특별한 변수 때문입니다.

.locals init (
    [0] class Program pg,
    [1] void* ptr,
    [2] int32& pinned
)

IL 코드를 보면, pg2 인스턴스를 저 pinned 특성이 적용된 [2]번 로컬 변수에 저장하는 코드가 나옵니다.

/* 0x000002A8 7C03000004   */ IL_0008: ldflda    int32 Program::'value' // Finds the address of a field in the object whose reference is currently on the evaluation stack.
/* 0x000002AD 0C           */ IL_000D: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

그런 다음, fixed 블록이 끝나는 지점에 단순히 [2]번 로컬 변수에 null을 대입해 pg2 인스턴스에 대한 참조를 해제합니다.

/* 0x000002B3 16           */ IL_0013: ldc.i4.0 // Pushes the integer value of 0 onto the evaluation stack as an int32.
/* 0x000002B4 E0           */ IL_0014: conv.u   // Converts the value on top of the evaluation stack to unsigned native int, and extends it to native int.
/* 0x000002B5 0C           */ IL_0015: stloc.2  // Pops the current value from the top of the evaluation stack and stores it in a the local variable list at index 2.

예상할 수 있듯이, Unsafe.AsPointer를 사용한 경우에는 void* 변수는 있지만, pinned 특성이 적용된 변수는 없습니다.




정리해 보면, Unsafe.AsPointer는 스택에 위치한 로컬 변수에 대해서만 안전한 포인터 위치를 반환합니다. 반면, 힙에 위치한 인스턴스의 경우, 즉 위의 예제에서처럼 pg.value를 Unsafe.AsPointer에 전달하는 것은 이후 사용을 조심해야 합니다. 왜냐하면, Unsafe.AsPointer를 호출한 시점의 pg.value가 위치한 주소를 반환은 하겠지만, 이후 그 포인터를 사용하는 사이 GC가 발생한다면 해당 참조 인스턴스는 메모리가 이동할 수 있기 때문입니다. 따라서, 힙에 할당된 인스턴스에 Unsafe.AsPointer를 사용하고 싶다면, 단순히 디버깅이나 간단한 테스트 용도의 목적 정도로만 한정해야 합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/1/2022]

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

비밀번호

댓글 작성자
 



2022-03-30 03시41분
[guest] 고정이 안되는걸 알고 질문드린건데 무슨차이로 인해 고정이 되고 안되는건지가 궁금했었거든요 오늘도 한수 배워갑니다 ^^
[guest]
2022-03-30 03시48분
[guest] 저런 매커니즘이라면 void DoSomething(Action<Intptr>) 형식의 Dynamicmethod를 빌드하여 사용하면 .net framework (7.0) 에서도 안정적인 pinning이 가능할듯하네요.
[guest]
2022-03-30 04시06분
[guest] void DoSomething<T>(T source, Action<Intptr> action) 이런식으로 DynamicMethod를 짜면 될것 같습니다. 개인적으로 ref 필드를 ref 없이 바꿀순 없을까? 라고 고민해본게 lambda 안에서 ref 로 넘겨야할때였는데요 이 방법으로 가능할지 내일 테스트 해봐야겠네요.
[guest]
2022-03-30 10시59분
@손님 테스트 결과가 기대되는군요. ^^ 개인적으로는, "저런 메커니즘"과 void DoSomething(Action<Intptr>) 형식의 DynamicMethod 간에 어떤 점으로 인해 pinning이 가능하다고 생각하는지 상상은 안 가지만...
정성태
2022-03-30 06시24분
[guest] 테스트 결과는 성공적이네요. 글을 올릴데가 없어서 질문 답변 게시판에 간단하게 인증샷 첨부했습니다.

https://www.sysnet.pe.kr/3/0/5635
[guest]

1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13449정성태11/21/20232351개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20232627닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20232487닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232419닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20232699Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20232456닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232492개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232322개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20232652닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232352Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20232844닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232462닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20232656닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20232893닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20232829닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20232631스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232357스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232406오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20232720스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20232612닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20232871닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20232923닷넷: 2151. C# 12 - ref readonly 매개변수
13427정성태10/18/20233101닷넷: 2150. C# 12 - 정적 문맥에서 인스턴스 멤버에 대한 nameof 접근 허용(Allow nameof to always access instance members from static context)
13426정성태10/13/20233284스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233099닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233078스크립트: 58. 파이썬 - async/await 기본 사용법
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...