Microsoft MVP성태의 닷넷 이야기
.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합 [링크 복사], [링크+제목 복사],
조회: 16991
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 18개 있습니다.)
.NET Framework: 1110. C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능 (DIM for Static Members)
; https://www.sysnet.pe.kr/2/0/12814

.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용
; https://www.sysnet.pe.kr/2/0/12839

.NET Framework: 1182. C# 11  - ref struct에 ref 필드를 허용
; https://www.sysnet.pe.kr/2/0/13015

.NET Framework: 2025. C# 11  - 원시 문자열 리터럴(raw string literals)
; https://www.sysnet.pe.kr/2/0/13085

.NET Framework: 2026. C# 11 - 문자열 보간 개선 2가지
; https://www.sysnet.pe.kr/2/0/13086

.NET Framework: 2030. C# 11 - UTF-8 문자열 리터럴
; https://www.sysnet.pe.kr/2/0/13096

.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자
; https://www.sysnet.pe.kr/2/0/13099

.NET Framework: 2032. C# 11 - shift 연산자 재정의에 대한 제약 완화 (Relaxing Shift Operator)
; https://www.sysnet.pe.kr/2/0/13100

.NET Framework: 2035. C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift)
; https://www.sysnet.pe.kr/2/0/13110

.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합
; https://www.sysnet.pe.kr/2/0/13111

.NET Framework: 2037. C# 11 - 목록 패턴(List patterns)
; https://www.sysnet.pe.kr/2/0/13112

.NET Framework: 2038. C# 11 - Span 타입에 대한 패턴 매칭 (Pattern matching on ReadOnlySpan<char>)
; https://www.sysnet.pe.kr/2/0/13113

.NET Framework: 2042. C# 11 - 파일 범위 내에서 유효한 타입 정의 (File-local types)
; https://www.sysnet.pe.kr/2/0/13117

.NET Framework: 2045. C# 11 - 메서드 매개 변수에 대한 nameof 지원
; https://www.sysnet.pe.kr/2/0/13122

.NET Framework: 2046. C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가
; https://www.sysnet.pe.kr/2/0/13123

.NET Framework: 2048. C# 11 - 구조체 필드의 자동 초기화(auto-default structs)
; https://www.sysnet.pe.kr/2/0/13125

.NET Framework: 2049. C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용
; https://www.sysnet.pe.kr/2/0/13126

.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
; https://www.sysnet.pe.kr/2/0/13276




C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합

(Visual Studio 2022 17.3 이후 버전에서 테스트할 수 있습니다.)

C# 9에 추가되었던 nint/nuint 타입은,

C# 9.0 - (4) 원시 크기 정수(Native ints)
; https://www.sysnet.pe.kr/2/0/12366

그 타입의 바탕이 각각 IntPtr/UIntPtr이었음에도 불구하고 각각 따로 개념을 유지했었습니다.

즉, IntPtr/UIntPtr은 여전히 포인터 연산을 위한 용도를 유지했고, nint/nuint는 단순히 플랫폼에 따라 바뀌는 "정수 타입"이라는 용도로 분리됐었습니다. 실제로 IntPtr/UIntPtr은 메모리의 포인터를 가리키는 것이므로 일반적인 정수형 타입에 적용되는 4칙 연산 등의 기능을 제공하지는 않았습니다.

IntPtr p1 = new IntPtr(5);
IntPtr p2 = new IntPtr(6);

// C# 10 이하에서는 아래의 코드가 모두 컴파일 오류
IntPtr p3 = p1 + p2; // error CS0019: Operator '+' cannot be applied to operands of type 'IntPtr' and 'IntPtr'
IntPtr p4 = p1 - p2; // error CS0019: Operator '-' cannot be applied to operands of type 'IntPtr' and 'IntPtr'
IntPtr p5 = p1 * p2; // error CS0019: Operator '*' cannot be applied to operands of type 'IntPtr' and 'IntPtr'
IntPtr p6 = p1 / p2; // error CS0019: Operator '/' cannot be applied to operands of type 'IntPtr' and 'IntPtr'

// 대신 +, -의 경우에는 IntPtr.AddIntPtr.Subtract 정적 메서드로 우회
//     /의 경우에는 .NET 7부터 IntPtr.DivRem 제공

반면 nint/nuint에 대해서는 기반 구현체였던 IntPtr/UIntPtr과는 달리 개념적으로는 정수형으로 취급했으므로 이것을 허용했습니다.

nint p1 = 5;
nint p2 = 6;

// 컴파일 가능
nint p3 = p1 + p2;
nint p4 = p1 - p2;
nint p5 = p1 * p2;
nint p6 = p1 / p2;

저렇게 개념적으로 나눴던 것을 C# 11부터는 동일한 타입으로 바꿨습니다. 즉, int 타입이 System.Int32의 C# alias였던 것처럼 nint와 nuint를 IntPtr/UIntPtr에 대한 alias로 취급하고, 이에 맞춰 기존의 IntPtr/UIntPtr 연산에 제한을 두었던 것을 말 그대로 정수형 타입으로 취급해 모두 허용하도록 바꿨습니다.

따라서 C# 11부터는 다음의 코드까지 모두 컴파일 가능합니다.

IntPtr p1 = new IntPtr(5);
IntPtr p2 = new IntPtr(6);

IntPtr p3 = p1 + p2; // C# 10 이하에서는 컴파일 오류
IntPtr p4 = p1 - p2; // C# 10 이하에서는 컴파일 오류
IntPtr p5 = p1 * p2; // C# 10 이하에서는 컴파일 오류
IntPtr p6 = p1 / p2; // C# 10 이하에서는 컴파일 오류
IntPtr p7 = p1 % p2; // C# 10 이하에서는 컴파일 오류

p1++; // C# 10 이하에서는 컴파일 오류
p1--; // C# 10 이하에서는 컴파일 오류

IntPtr p8 = -p1; // C# 10 이하에서는 컴파일 오류
IntPtr p9 = ~p1; // C# 10 이하에서는 컴파일 오류
IntPtr p10 = p1 << 2; // C# 10 이하에서는 컴파일 오류
IntPtr p11 = p1 >> 2; // C# 10 이하에서는 컴파일 오류
IntPtr p12 = p1 >>> 2; // C# 10 이하에서는 컴파일 오류

Console.WriteLine(p1 > p2); // C# 10 이하에서는 컴파일 오류
Console.WriteLine(p1 >= p2); // C# 10 이하에서는 컴파일 오류
Console.WriteLine(p1 < p2); // C# 10 이하에서는 컴파일 오류
Console.WriteLine(p1 <= p2); // C# 10 이하에서는 컴파일 오류

Console.WriteLine(p1 & p2); // C# 10 이하에서는 컴파일 오류
Console.WriteLine(p1 | p2); // C# 10 이하에서는 컴파일 오류
Console.WriteLine(p1 ^ p2); // C# 10 이하에서는 컴파일 오류

int[] n = new int[500];
Console.WriteLine(n[p1]); // C# 10 이하에서는 컴파일 오류

IntPtr p = new nint(6); // C# 10 이하에서는 컴파일 오류

Console.WriteLine(nint.Zero); // C# 10 이하에서는 컴파일 오류
Console.WriteLine(nuint.Zero); // C# 10 이하에서는 컴파일 오류

재미있는 것은, C# 11의 언어적 차원에서 nint/nuint가 IntPtr/UIntPtr의 alias로 취급은 되지만 결국 IntPtr/UIntPtr 타입의 구현 코드에 영향을 받는 것이므로 반드시 .NET 7의 새로운 BCL을 필요로 한다는 점입니다. 이로 인해 .NET 6 이하의 프로젝트를 대상으로는 C# 11로 컴파일해도 위의 코드들은 모두 컴파일 오류가 발생합니다. 즉, C# 11로 컴파일해도 대상 런타임이 .NET 6 이하라면 기존의 방식처럼 빌드하게 되므로 alias 취급을 받지 못하는 것입니다.




C# 11 - 인터페이스 내에 정적 추상 메서드 정의 가능 (공식 문서, Static Abstract Members In Interfaces C# 10 Preview)
; https://www.sysnet.pe.kr/2/0/12814

C# 11 - 제네릭 타입의 특성 적용 (공식 문서, Generic attributes)
; https://www.sysnet.pe.kr/2/0/12839

C# 11 - 사용자 정의 checked 연산자 (공식 문서, Checked user-defined operators)
; https://www.sysnet.pe.kr/2/0/13099

C# 11 - shift 연산자 재정의에 대한 제약 완화 (공식 문서, Relaxing Shift Operator)
; https://www.sysnet.pe.kr/2/0/13100

C# 11 - IntPtr/UIntPtr과 nint/unint의 통합 (공식 문서, Numeric IntPtr)
; https://www.sysnet.pe.kr/2/0/13111

C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift) (공식 문서, Unsigned right shift operator)
; https://www.sysnet.pe.kr/2/0/13110

C# 11 - 원시 문자열 리터럴 (공식 문서, raw string literals)
; https://www.sysnet.pe.kr/2/0/13085

C# 11 - 문자열 보간 개선 2가지 (공식 문서, Allow new-lines in all interpolations)
; https://www.sysnet.pe.kr/2/0/13086

C# 11 - 목록 패턴 (공식 문서, List patterns)
; https://www.sysnet.pe.kr/2/0/13112

C# 11 - Span 타입에 대한 패턴 매칭 (공식 문서, Pattern matching on ReadOnlySpan<char>)
; https://www.sysnet.pe.kr/2/0/13113

C# 11 - Utf8 문자열 리터럴 지원 (공식 문서, Utf8 Strings Literals)
; https://www.sysnet.pe.kr/2/0/13096

C# 11 - ref struct에 ref 필드를 허용 (공식 문서, ref fields)
; https://www.sysnet.pe.kr/2/0/13015

C# 11 - 파일 범위 내에서 유효한 타입 정의 (공식 문서, File-local types)
; https://www.sysnet.pe.kr/2/0/13117

C# 11 - 메서드 매개 변수에 대한 nameof 지원 (공식 문서, nameof(parameter))
; https://www.sysnet.pe.kr/2/0/13122

C# 11 - 멤버(속성/필드)에 지정할 수 있는 required 예약어 추가 (공식 문서, Required members)
; https://www.sysnet.pe.kr/2/0/13123

C# 11 - 구조체 필드의 자동 초기화 (공식 문서, auto-default structs)
; https://www.sysnet.pe.kr/2/0/13125

C# 11 - 정적 메서드에 대한 delegate 처리 시 cache 적용 (공식 문서, Cache delegates for static method group)
; https://www.sysnet.pe.kr/2/0/13126

Language Feature Status
; https://github.com/dotnet/roslyn/blob/main/docs/Language%20Feature%20Status.md




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







[최초 등록일: ]
[최종 수정일: 5/5/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)
13768정성태10/15/20245395C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/20244768오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/20244552C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/20245262오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/20245626Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/20244985Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/20245009Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/20244914오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/20245448Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20246363C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/20245578오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/20245514닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/20245624오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/20246022닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/20245573닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
13753정성태10/4/20245593Linux: 81. Linux - PATH 환경변수의 적용 규칙
13752정성태10/2/20246272닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능 [6]파일 다운로드1
13751정성태10/2/20245402C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20245293C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20245535닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20245743닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/20245591닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20245685오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20245545Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
13744정성태9/27/20245974닷넷: 2299. C# - Windows Hello 사용자 인증 다이얼로그 표시하기파일 다운로드1
13743정성태9/26/20246427닷넷: 2298. C# - Console 프로젝트에서의 await 대상으로 Main 스레드 활용하는 방법 [1]
1  2  3  4  5  6  [7]  8  9  10  11  12  13  14  15  ...