Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2101. C# 11의 ref 필드 설명 [링크 복사], [링크+제목 복사]
조회: 4660
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)

C# 11의 ref 필드 설명

사실 ref struct도 잘 쓰지 않는 상황에서 ref 필드는 더더욱 쓸 사례가 없습니다. 제 생각으로는, 아마 이번에도 외부 개발사보다는 마이크로소프트 스스로가 제일 잘 쓸 만한 문법으로 보이는데요, 그나저나 도대체 이걸 누가 제안한 것일까요? 아마도 ref 필드에 대한 처음 요구 사항은 아래의 이슈였을 것입니다.

Allow ref struct to contain ref fields
; https://github.com/dotnet/runtime/issues/32060

이슈 생성자는 다름 아닌 마이크로소프트의 직원이군요. ^^ 어쨌든 원래의 요구 사항은 "System.ByReference<T>" 타입을 internal이 아닌 public으로 만들어 달라는 것에 불과했습니다.

이해를 돕기 위해 좀 더 설명을 추가해 볼까요? ^^

이미 Span<T> 등의 타입에서는 마이크로소프트가 "(C# 11의) ref field"와 동일한 기능을 System.ByReference<T>라는 타입을 이용해 내부적으로 사용하고 있었습니다.

corert/src/System.Private.CoreLib/shared/System/Span.cs 
; https://github.com/dotnet/corert/blob/master/src/System.Private.CoreLib/shared/System/Span.cs

public readonly ref struct Span<T>
{
    internal readonly ByReference<T> _pointer;
    private readonly int _length;

    // ...[생략]...
}

여기서 재미있는 것은, 위의 코드에서 사용한 ByReference<T>의 소스 코드입니다.

corert/src/System.Private.CoreLib/shared/System/ByReference.cs 
; https://github.com/dotnet/corert/blob/master/src/System.Private.CoreLib/shared/System/ByReference.cs

// ByReference<T> is meant to be used to represent "ref T" fields. It is working
// around lack of first class support for byref fields in C# and IL. The JIT and
// type loader has special handling for it that turns it into a thin wrapper around ref T.
[NonVersionable]
internal readonly ref struct ByReference<T>
{
#pragma warning disable CA1823, 169 // private field '{blah}' is never used
    private readonly IntPtr _value;
#pragma warning restore CA1823, 169

    [Intrinsic]
    public ByReference(ref T value)
    {
        // Implemented as a JIT intrinsic - This default implementation is for
        // completeness and to provide a concrete error if called via reflection
        // or if intrinsic is missed.
        throw new PlatformNotSupportedException();
    }

    public ref T Value
    {
        // Implemented as a JIT intrinsic - This default implementation is for
        // completeness and to provide a concrete error if called via reflection
        // or if the intrinsic is missed.
        [Intrinsic]
        get => throw new PlatformNotSupportedException();
    }
}

보는 바와 같이 구현 코드가 없음에도 이것이 잘 동작하는 이유는, JIT 컴파일러에 의해 "ref T"와 같은 역할로 번역되기 때문입니다. 아마도 마이크로소프트는 저렇게 구현한 ByReference를 단순히 public으로 접근자만 바꿔서 제공하기에는 많이 찜찜했을 것입니다. ^^ 그리하여 ref 필드라는 유형으로 공식 지원하게 되었고, 실제로 그 문법을 활용한 첫 번째 사례가 바로 .NET 7의 Span<T> 타입입니다.

runtime/src/libraries/System.Private.CoreLib/src/System/Span.cs 
; https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Span.cs

public readonly ref struct Span<T>
{
    internal readonly ref T _reference;
    private readonly int _length;

    // ...[생략]...
}

그러고 보니, C# 7.2부터 마이크로소프트의 아주 특별한 혜택을 받아 탄생한 Span<T> 타입이 이제서야 비로소 순수 C# 문법으로 만드는 것이 가능해졌습니다.




재미있는 건, ref 필드가 나오기 전에도 이미 기존 문법과 BCL의 조합으로 동일한 기능을 구현할 수 있었다는 점입니다. 가령 "Allow ref struct to contain ref fields" 이슈에도 나오지만,

using System.Runtime.InteropServices;

internal class Program
{
    static void Main(string[] args)
    {
        MyData data = new MyData();

        Console.WriteLine(data.n.Value); // System.NullReferenceException: 'Object reference not set to an instance of an object.'
    }
}

public ref struct MyData
{
    public FakeByReference<int> n; // == ref int n; 코드와 동일

    public MyData(ref int n1)
    {
        n = new FakeByReference<int>(ref n1);
    }
}

public readonly ref struct FakeByReference<T>
{
    private readonly Span<T> span;

    public FakeByReference(ref T value)
    {
        span = MemoryMarshal.CreateSpan(ref value, 1);
    }

    public ref T Value => ref MemoryMarshal.GetReference(span);
}

ref struct + MemoryMarshal.CreateSpan/MemoryMarshal.GetReference로 구현을 할 수 있었고, 예전에 소개한 글에서도,

C# 11에 추가된 ref 필드의 (우회) 구현 방법
; https://www.sysnet.pe.kr/2/0/13016

unsafe ref struct + Unsafe.AsPointer/Unsafe.AsRef로 구현했었습니다. 최초 이슈를 제기했던 "Allow ref struct to contain ref fields" 글에서는 이러한 경우를 바탕으로 다음과 같이 요구합니다.


Given that this is already possible with existing APIs, as shown above, but it's less performant than the original ByReference<T>, more verbose and more error prone, why not just make the original ByReference<T> type public so everyone can use it with no need to reinvent the wheel?


"C# - 관리 포인터로서의 ref 예약어 의미" 글에서 이미 설명했듯이, ref를 이용한 관리 포인터 사용은 스택에 있는 인스턴스를 가리키는 상황에서 C# 컴파일러에 의해 한 번 더 안정성 체크를 할 수 있는 기회를 부여합니다.

유사한 상황이 ref 필드에도 발생한 것인데요, 위에서 든 ref field에 대한 우회 방법들은 성능도 떨어지고 오류 발생 가능성도 내포하고 있습니다. 그런데, 만약 이것을 C# 컴파일러에서 "ref field" 문법으로 정식 지원을 한다면 기존의 ref 관리 포인터와 마찬가지로 C# 컴파일러의 안정성 체크에서 유효하지 않은 코드들은 자연스럽게 걸러질 것이므로 나쁘지 않은 요구 사항입니다. ^^




이렇게 우여곡절 끝에 탄생한 ref 필드 덕분에 이제 C# 컴파일러는 아래와 같은 전형적인 사례에서 스택 변수의 scope를 계산해 컴파일 에러를 낼 수 있게 되었습니다.

internal class Program
{
    static void Main(string[] args) { }

    static public MyType GetData()
    {
        int n = 5;

        var t = new MyType(ref n);
        return t; // 컴파일 오류: error CS8352: Cannot use variable 't' in this context because it may expose referenced variables outside of their declaration scope
    }
}

public ref struct MyType
{
    ref int _n;
    public MyType(ref int target)
    {
        _n = ref target;
    }
}

GetData 메서드가 실행 중일 때만 유효한 "int n" 변수가 메서드의 반환값으로 사용되는 MyType에 참조가 전해진 것을 막을 수 있게 되었습니다. 일면 납득이 가시죠? ^^

그런데, 위의 오류 메시지를 보면 "it may expose ..."라는 문구가 나옵니다. 왜냐하면, GetData 메서드를 컴파일하는 입장에서 MyType이 외부 어셈블리에 정의된 것일 수도 있으므로 그렇게 판정할 수밖에 없습니다. 왜냐하면, MyType이 다음과 같이 구성된 경우라면,

public ref struct MyType 
{
    public MyType(ref int target) { }
}

이번에는 문제가 없습니다. 즉, ref struct의 생성자에 ref 인자를 전달하는 것만으로도 C# 컴파일러는 보수적으로 컴파일 에러를 발생시키는 겁니다.

이와는 달리 "C# - ref 필드로 ref struct 타입을 허용하지 않는 이유" 글에서도 들었던 사례처럼 ref 필드에 대한 C# 컴파일러의 유효성 체크 구현이 그리 완벽하진 않은 경우도 있습니다. 가령, 위의 소스 코드에 살짝 변화만 가해주면,

private static void Case1()
{
    int n = 5;
    MyType data;
    data = new MyType(ref n); // error CS8168: Cannot return local 'n' by reference because it is not a ref local
                              // error CS8347: Cannot use a result of 'MyData.MyData(ref int)' in this context because it may expose variables referenced by parameter 'n1' outside of their declaration scope

    Console.WriteLine(data.value);
}

private static void Case2()
{
    int n = 5;

    MyType data = new MyType(ref n); // 이 코드는 잘 통과했으면서!
    Console.WriteLine(data.value);
}

저렇게 알 수 없는 컴파일 오류가 발생해 버립니다. 음... 아마도 차차 나아지겠죠?!!! ^^ (아니면 제가 뭘 몰라서 그런 걸까요? ^^ 혹시 저 차이점을 아시는 분은 덧글 부탁드립니다.)




휴~~~ 예전에 그냥 단순히 소개만 하고 지나갔던 것을,

C# 11  - ref struct에 ref 필드를 허용
; https://www.sysnet.pe.kr/2/0/13015

이제서야 여러 가지 이야기와 함께 풀어냈습니다. ^^

C# - 관리 포인터로서의 ref 예약어 의미
; https://www.sysnet.pe.kr/2/0/13273

C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
; https://www.sysnet.pe.kr/2/0/13274

그래도 아직 scoped 신규 예약어에 대한 이야기가 남았는데요, ^^ 그건 다른 글에서 다뤄보겠습니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/6/2023]

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

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13220정성태1/19/20234281오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233856Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233778VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234381디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234647디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236147Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235722.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235259오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235024기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235106웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234130Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234022Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20233956.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224263.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224469.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224869.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224147.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224270.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224643기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225266오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224146오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224414개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224307.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224264.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
13196정성태12/16/20224393.NET Framework: 2078. .NET Core/5+를 위한 SGen(Microsoft.XmlSerializer.Generator) 사용법
13195정성태12/15/20224987개발 환경 구성: 655. docker - bridge 네트워크 모드에서 컨테이너 간 통신 시 --link 옵션 권장 이유
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...