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)
13262정성태2/15/202313474디버깅 기술: 191. dnSpy를 이용한 (소스 코드가 없는) 닷넷 응용 프로그램 디버깅 방법 [1]
13261정성태2/15/202312955Windows: 224. Visual Studio - 영문 폰트가 Fullwidth Latin Character로 바뀌는 문제
13260정성태2/14/202312206오류 유형: 847. ilasm.exe 컴파일 오류 - error : syntax error at token '-' in ... -inf
13259정성태2/14/202312148.NET Framework: 2095. C# - .NET5부터 도입된 CollectionsMarshal
13258정성태2/13/202312904오류 유형: 846. .NET Framework 4.8 Developer Pack 설치 실패 - 0x81f40001
13257정성태2/13/202312316.NET Framework: 2094. C# - Job에 Process 포함하는 방법 [1]파일 다운로드1
13256정성태2/10/202312458개발 환경 구성: 665. WSL 2의 네트워크 통신 방법 - 두 번째 이야기
13255정성태2/10/202312665오류 유형: 845. gihub - windows2022 이미지에서 .NET Framework 4.5.2 미만의 프로젝트에 대한 빌드 오류
13254정성태2/10/202312558Windows: 223. (WMI 쿼리를 위한) PowerShell 문자열 escape 처리
13253정성태2/9/202313700Windows: 222. C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법파일 다운로드1
13252정성태2/9/202311588오류 유형: 844. ssh로 명령어 수행 시 멈춤 현상
13251정성태2/8/202312183스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/202313767오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/202314363오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/202311047오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/202312596VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/202312428개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/202312973.NET Framework: 2093. C# - PKCS#8 PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/202312082VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/202313215디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/202312070디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/202310653디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/202311336디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/202310699디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/202314978.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/202314289.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
... 16  17  18  19  20  21  22  23  24  25  26  [27]  28  29  30  ...