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

비밀번호

댓글 작성자
 




1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13818정성태11/15/20245257Windows: 272. Windows 11 24H2 - sudo 추가
13817정성태11/14/20244919Linux: 106. eBPF / bpf2go - (BPF_MAP_TYPE_HASH) Map을 이용한 전역 변수 구현
13816정성태11/14/20245382닷넷: 2312. C#, C++ - Windows / Linux 환경의 Thread Name 설정파일 다운로드1
13815정성태11/13/20244804Linux: 105. eBPF - bpf2go에서 전역 변수 설정 방법
13814정성태11/13/20245277닷넷: 2311. C# - Windows / Linux 환경에서 Native Thread ID 가져오기파일 다운로드1
13813정성태11/12/20245014닷넷: 2310. .NET의 Rune 타입과 emoji 표현파일 다운로드1
13812정성태11/11/20245245오류 유형: 933. Active Directory - The forest functional level is not supported.
13811정성태11/11/20244846Linux: 104. Linux - COLUMNS 환경변수가 언제나 80으로 설정되는 환경
13810정성태11/10/20245374Linux: 103. eBPF (bpf2go) - Tracepoint를 이용한 트레이스 (BPF_PROG_TYPE_TRACEPOINT)
13809정성태11/10/20245250Windows: 271. 윈도우 서버 2025 마이그레이션
13808정성태11/9/20245249오류 유형: 932. Linux - 커널 업그레이드 후 "error: bad shim signature" 오류 발생
13807정성태11/9/20244983Linux: 102. Linux - 커널 이미지 파일 서명 (Ubuntu 환경)
13806정성태11/8/20244893Windows: 270. 어댑터 상세 정보(Network Connection Details) 창의 내용이 비어 있는 경우
13805정성태11/8/20244734오류 유형: 931. Active Directory의 adprep 또는 복제가 안 되는 경우
13804정성태11/7/20245362Linux: 101. eBPF 함수의 인자를 다루는 방법
13803정성태11/7/20245309닷넷: 2309. C# - .NET Core에서 바뀐 DateTime.Ticks의 정밀도
13802정성태11/6/20245691Windows: 269. GetSystemTimeAsFileTime과 GetSystemTimePreciseAsFileTime의 차이점파일 다운로드1
13801정성태11/5/20245480Linux: 100. eBPF의 2가지 방식 - libbcc와 libbpf(CO-RE)
13800정성태11/3/20246315닷넷: 2308. C# - ICU 라이브러리를 활용한 문자열의 대소문자 변환 [2]파일 다운로드1
13799정성태11/2/20244891개발 환경 구성: 732. 모바일 웹 브라우저에서 유니코드 문자가 표시되지 않는 경우
13798정성태11/2/20245490개발 환경 구성: 731. 유니코드 - 출력 예시 및 폰트 찾기
13797정성태11/1/20245484C/C++: 185. C++ - 문자열의 대소문자를 변환하는 transform + std::tolower/toupper 방식의 문제점파일 다운로드1
13796정성태10/31/20245368C/C++: 184. C++ - ICU dll을 이용하는 예제 코드 (Windows)파일 다운로드1
13795정성태10/31/20245163Windows: 268. Windows - 리눅스 환경처럼 공백으로 끝나는 프롬프트 만들기
13794정성태10/30/20245261닷넷: 2307. C# - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법
13793정성태10/28/20245125C/C++: 183. C++ - 윈도우에서 한글(및 유니코드)을 포함한 콘솔 프로그램을 컴파일 및 실행하는 방법
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...