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

C# - safe/unsafe 문맥에 대한 C# 13의 (하위 호환을 깨는) 변화

이 글의 실습은 현재(2024-08-05) Visual Studio 2022 Preview 버전(최소 17.11.p2)에서만 가능합니다.




Unsafe 문맥은,

23 Unsafe code
; https://github.com/dotnet/csharpstandard/blob/ee38c3fa94375cdac119c9462b604d3a02a5fcd2/standard/unsafe-code.md#232-unsafe-contexts

Other than establishing an unsafe context, thus permitting the use of pointer types, the unsafe modifier has no effect on a type or a member.


문서에도 나오듯이, 포인터를 사용할 수 있도록 허용하는 것 외에는 별달리 특별한 기능은 없습니다. 그리고 그에 대한 문맥 설정은 unsafe 예약어를 통해 블록으로 설정할 수 있고,

void Method() // 메서드 전체 구간에서는 safe 문맥
{
    unsafe // 메서드 내에서 아래의 블록 내에서만 unsafe 문맥으로 바뀜
    {
        int* p = stackalloc int[10];
    }
}

상위 구간에서 설정되면 하위 영역은 자연스럽게 문맥을 이어받게 됩니다.

unsafe void Method() // 메서드 전체 구간에 unsafe 문맥
{
    int* p = stackalloc int[10]; // 따라서 별도의 unsafe 블록 없이도 포인터 사용 가능

    void LocalFunc() // 메서드가 포함하는 로컬 함수는 그 메서드를 포함한 문맥을 상속
    {
        int* p2 = stackalloc int[10]; // 따라서 별도의 unsafe 블록 없이도 포인터 사용 가능
    }
}

public unsafe class MyClass // 타입의 전체 구간에 unsafe 문맥
{
    void Method() 
    {
        int* p = stackalloc int[10]; // 따라서 별도의 unsafe 블록 없이도 포인터 사용 가능
    }
}

재미있는 건 unsafe 예약어는 있어도 safe 예약어는 없다는 점입니다. 이로 인해 unsafe 문맥 내에서 특정 영역을 다시 safe 문맥으로 돌리는 방법은 없습니다.

그런데, 이에 대한 예외가 하나(?) 있는데요,

13.3.1 General
; https://github.com/dotnet/csharpstandard/blob/ee38c3fa94375cdac119c9462b604d3a02a5fcd2/standard/statements.md#1331-general

It is a compile-time error for an iterator block to contain an unsafe context (§23.2). An iterator block always defines a safe context, even when its declaration is nested in an unsafe context.


iterator 메서드의 경우 내부 block을 무조건 safe 문맥으로 설정한다는 점입니다. 그래서 아래와 같은 코드의 경우,

using System.Collections.Generic;

unsafe public class Program
{
    static void Main(string[] args)
    {
        int* p = stackalloc int[2]; // 일반 메서드는 타입에 지정된 unsafe 문맥이 적용되지만,
    }

    public static IEnumerator<int> GetNumbers()
    { // iterator 메서드의 내부 블록은 무조건 safe 문맥 적용

        int* p = stackalloc int[2]; // 컴파일 오류 - error CS1629: 반복기에는 안전하지 않은 코드를 사용할 수 없습니다.
                                    // Unsafe code may not appear in iterators

        yield return 1;
    }
}

(타입에 지정한 unsafe의 영향으로) Main 메서드 내에서는 unsafe 코드가 허용되지만 GetNumbers iterator 메서드 블록 내에서는 CS1629 컴파일 오류가 발생합니다. 게다가 (C# 12 이하에서는) 아예 unsafe 블록 자체를 내부에 허용하지 않기 때문에 결과적으로 포인터를 사용한 코드를 작성할 수 없습니다.




iterator 메서드에 특이한 점이 하나 더 있다면, safe 문맥이라고 강제로 적용됨에도 불구하고 그 메서드가 포함한 로컬 함수는 iterator 메서드가 아닌 상위 범위의 문맥을 상속한다는 점입니다. 그래서 다음과 같은 코드는 허용이 됩니다.

unsafe public class Program // unsafe 문맥
{
    static void Main(string[] args)
    {
        int* p = stackalloc int[2];
    }

    public static IEnumerator<int> GetNumbers()
    { // iterator 메서드의 내부 블록은 무조건 safe 문맥 적용

        LocalFunc();

        yield return 1;

        void LocalFunc() // 하지만, 로컬 함수는 타입에 지정했던 unsafe 문맥을 상속
        {
            int* p = stackalloc int[2]; // 포인터 코드 사용 가능
        }
    }
}

약간 혼란스럽죠? ^^ 문서에 의하면 위의 경우 (C# 12 이하의) Roslyn은 iterator 메서드를 실제론 unsafe 문맥으로 처리하면서도, 단지 내부에서만 unsafe 구문을 허용하지 않는 식으로 처리한다고 합니다.

C# 13 컴파일러에서 변화된 것이 바로 저 규칙입니다. 블록 내부 전체에서 unsafe를 사용하지 못하도록 강제하는 것이 아닌, 일부 영역을 unsafe로 지정 가능하도록 바뀌었고 내부에서 정의하는 로컬 함수의 문맥도 iterator 블록의 safe 문맥을 따라가도록 했습니다. 그래서 저 코드를 그대로 C# 13에서 빌드하면,

unsafe public class Program
{
    public static IEnumerator<int> GetNumbers()
    { // 여기서 다시 safe 문맥으로 바뀌고,
        LocalFunc();

        yield return 1;

        void LocalFunc() // 로컬 함수도 safe 문맥이므로,
        {
            int* p = stackalloc int[2]; // 컴파일 에러 - error CS0214: Pointers and fixed size buffers may only be used in an unsafe context
        }
    }
}

CS0214 컴파일 에러가 발생합니다. 즉, iterator 메서드에 강제로 적용된 safe 문맥을 로컬 함수(위의 경우 LocalFunc)에 내려주므로 포인터 코드를 사용할 수 없게 되었습니다.

이렇게 하위 호환이 깨지긴 했지만 해당 영역을 unsafe 문맥으로 지정하는 것으로,

/* 또는, unsafe */ void LocalFunc()
{
    unsafe
    {
        int* p = stackalloc int[2];
    }
}

쉽게 해결할 수는 있습니다.




이번 글은 사실 C# 13의 "Allow ref and unsafe in iterators and async"에 명시하고 있는 "Breaking changes"의 내용에 포함된 내용을 정리한 것입니다.

Allow ref and unsafe in iterators and async
- Breaking changes
; https://github.com/dotnet/csharplang/blob/main/proposals/ref-unsafe-in-iterators-async.md#breaking-changes

그리고 보다 더 복잡한 규칙은 다음과 같은데요, 이번 글을 이해하셨다면 눈에 들어올 것입니다. ^^

// https://github.com/dotnet/csharplang/blob/main/proposals/ref-unsafe-in-iterators-async.md#detailed-design

using System.Collections.Generic;
using System.Threading.Tasks;

class A : System.Attribute { }
unsafe partial class C1
{ // unsafe context
    [/* unsafe context */ A]
    IEnumerable<int> M1(
        /* unsafe context */ int*[] x)
    { // safe context (this is the iterator block implementing the iterator)
        yield return 1;
    }
    IEnumerable<int> M2()
    { // safe context (this is the iterator block implementing the iterator)
        unsafe
        { // unsafe context
            { // unsafe context (this is *not* the block implementing the iterator)
                yield return 1; // error: `yield return` in unsafe context
            }
        }
    }
    [/* unsafe context */ A]
    unsafe IEnumerable<int> M3(
        /* unsafe context */ int*[] x)
    { // safe context
        yield return 1;
    }
    [/* unsafe context */ A]
    IEnumerable<int> this[
        /* unsafe context */ int*[] x]
    { // unsafe context
        get
        { // safe context
            yield return 1;
        }
        set { /* unsafe context */ }
    }
    [/* unsafe context */ A]
    unsafe IEnumerable<int> this[
        /* unsafe context */ long*[] x]
    { // unsafe context (the iterator declaration is unsafe)
        get
        { // safe context
            yield return 1;
        }
        set { /* unsafe context */ }
    }
    IEnumerable<int> M4()
    {
        yield return 1;
        var lam1 = async () =>
        { // safe context
          // spec violation: in Roslyn, this is an unsafe context in LangVersion 12 and lower
            await Task.Yield(); // error in C# 12, allowed in C# 13
            int* p = null; // error in both C# 12 and C# 13 (unsafe in iterator)
        };
        unsafe
        {
            var lam2 = () =>
            { // unsafe context, lambda cannot be an iterator
                yield return 1; // error: yield cannot be used in lambda
            };
        }
        async void local()
        { // safe context
          // spec violation: in Roslyn, this is an unsafe context in LangVersion 12 and lower
            await Task.Yield(); // error in C# 12, allowed in C# 13
            int* p = null; // allowed in C# 12, error in C# 13 (breaking change in Roslyn)
        }
        local();
    }
    public partial IEnumerable<int> M5() // unsafe context (inherits from parent)
    { // safe context
        yield return 1;
    }
}
partial class C1
{
    public partial IEnumerable<int> M5(); // safe context (inherits from parent)
}
class C2
{ // safe context
    [/* unsafe context */ A]
    unsafe IEnumerable<int> M(
        /* unsafe context */ int*[] x)
    { // safe context
        yield return 1;
    }
    unsafe IEnumerable<int> this[
        /* unsafe context */ int*[] x]
    { // unsafe context
        get
        { // safe context
            yield return 1;
        }
        set { /* unsafe context */ }
    }
}




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 9/5/2024]

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)
13337정성태5/5/202312839Linux: 59. dockerfile - docker exec로 container에 접속 시 자동으로 실행되는 코드 적용
13336정성태5/4/202312364.NET Framework: 2111. C# - 바이너리 출력 디렉터리와 연관된 csproj 설정
13335정성태4/30/202313265.NET Framework: 2110. C# - FFmpeg.AutoGen 라이브러리를 이용한 기본 프로젝트 구성 - Windows Forms파일 다운로드1
13334정성태4/29/202312274Windows: 250. Win32 C/C++ - Modal 메시지 루프 내에서 SetWindowsHookEx를 이용한 Thread 메시지 처리 방법
13333정성태4/28/202310804Windows: 249. Win32 C/C++ - 대화창 템플릿을 런타임에 코딩해서 사용파일 다운로드1
13332정성태4/27/202311096Windows: 248. Win32 C/C++ - 대화창을 위한 메시지 루프 사용자 정의파일 다운로드1
13331정성태4/27/202310712오류 유형: 856. dockerfile - 구 버전의 .NET Core 이미지 사용 시 apt update 오류
13330정성태4/26/202311286Windows: 247. Win32 C/C++ - CS_GLOBALCLASS 설명
13329정성태4/24/202311464Windows: 246. Win32 C/C++ - 직접 띄운 대화창 템플릿을 위한 Modal 메시지 루프 생성파일 다운로드1
13328정성태4/19/202311291VS.NET IDE: 184. Visual Studio - Fine Code Coverage에서 동작하지 않는 Fake/Shim 테스트
13327정성태4/19/202311499VS.NET IDE: 183. C# - .NET Core/5+ 환경에서 Fakes를 이용한 단위 테스트 방법
13326정성태4/18/202314072.NET Framework: 2109. C# - 닷넷 응용 프로그램에서 SQLite 사용 (System.Data.SQLite) [1]파일 다운로드1
13325정성태4/18/202312221스크립트: 48. 파이썬 - PostgreSQL의 with 문을 사용한 경우 연결 개체 누수
13324정성태4/17/202312472.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석파일 다운로드1
13323정성태4/16/202312112개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
13322정성태4/15/202313656VS.NET IDE: 182. Visual Studio - 32비트로만 빌드된 ActiveX와 작업해야 한다면?
13321정성태4/14/202311562개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
13320정성태4/13/202311337개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
13319정성태4/12/202312313개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
13318정성태4/11/202311989개발 환경 구성: 673. JetBrains IDE에서 "Squash Commits..." 메뉴가 비활성화된 경우
13317정성태4/11/202312180오류 유형: 855. WSL 2 Ubuntu 20.04 - error: cannot communicate with server: Post http://localhost/v2/snaps/...
13316정성태4/10/202310662오류 유형: 854. docker-compose 시 "json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)" 오류 발생
13315정성태4/10/202311597Windows: 245. Win32 - 시간 만료를 갖는 컨텍스트 메뉴와 윈도우 메시지의 영역별 정의파일 다운로드1
13314정성태4/9/202312452개발 환경 구성: 672. DosBox를 이용한 Turbo C, Windows 3.1 설치 [1]
13313정성태4/9/202311879개발 환경 구성: 671. Hyper-V VM에 Turbo C 2.0 설치 [2]
13312정성태4/8/202311630Windows: 244. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (개선된 버전)파일 다운로드1
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...