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)
13516정성태1/7/20249684닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20249631닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20249526개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20249623닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20249873개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20249618닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20249363닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/202410548오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/202410038오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/202411122닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/202310269닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/202312103닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/202311215닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/202310391Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/202310931닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/202310270개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
13500정성태12/24/202310786디버깅 기술: 194. Windbg - x64 가상 주소를 물리 주소로 변환
13498정성태12/23/202312455닷넷: 2186. 한국투자증권 KIS Developers OpenAPI의 C# 래퍼 버전 - eFriendOpenAPI NuGet 패키지
13497정성태12/22/202310626오류 유형: 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/202310558Linux: 66. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (gdb)
13495정성태12/20/202310791Linux: 65. clang++로 공유 라이브러리의 -static 옵션 빌드가 가능할까요?
13494정성태12/20/202310896Linux: 64. Linux 응용 프로그램의 (C++) so 의존성 줄이기(ReleaseMinDependency) - 두 번째 이야기
13493정성태12/19/202310989닷넷: 2185. C# - object를 QueryString으로 직렬화하는 방법
13492정성태12/19/202310377개발 환경 구성: 699. WSL에 nopCommerce 예제 구성
13491정성태12/19/20239380Linux: 63. 리눅스 - 다중 그룹 또는 사용자를 리소스에 권한 부여
13490정성태12/19/202310105개발 환경 구성: 698. Golang - GLIBC 의존을 없애는 정적 빌드 방법
... 16  [17]  18  19  20  21  22  23  24  25  26  27  28  29  30  ...