Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2101. C# 11의 ref 필드 설명 [링크 복사], [링크+제목 복사]
조회: 4766
글쓴 사람
정성태 (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

비밀번호

댓글 작성자
 




1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13507정성태1/2/20242816닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232371닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232909닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232495닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232363Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232459닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232275개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/20232328디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/20233012닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/20232430오류 유형: 885. Visual Studiio - error : Could not connect to the remote system. Please verify your connection settings, and that your machine is on the network and reachable.
13496정성태12/21/20232415Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/20232380Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/20232525Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/20232617닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/20232305개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20232241Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/20232363개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
13489정성태12/19/20232147개발 환경 구성: 697. GoLand에서 ldflags 지정 방법
13488정성태12/18/20232079오류 유형: 884. HTTP 500.0 - 명령행에서 실행한 ASP.NET Core 응용 프로그램을 실행하는 방법
13487정성태12/16/20232395개발 환경 구성: 696. C# - 리눅스용 AOT 빌드를 docker에서 수행 [1]
13486정성태12/15/20232210개발 환경 구성: 695. Nuget config 파일에 값 설정/삭제 방법
13485정성태12/15/20232094오류 유형: 883. dotnet build/restore - error : Root element is missing
13484정성태12/14/20232170개발 환경 구성: 694. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법
13483정성태12/14/20232310닷넷: 2184. C# - 하나의 resource 파일을 여러 프로그램에서 (AOT 시에도) 사용하는 방법파일 다운로드1
13482정성태12/13/20232894닷넷: 2183. C# - eFriend Expert OCX 예제를 .NET Core/5+ Console App에서 사용하는 방법 [2]파일 다운로드1
13481정성태12/13/20232280개발 환경 구성: 693. msbuild - .NET Core/5+ 프로젝트에서 resgen을 이용한 리소스 파일 생성 방법파일 다운로드1
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...