Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 11개 있습니다.)
.NET Framework: 404. 리플렉션을 이용해 닷넷 LicenseManager를 우회할 수 있는 사례
; https://www.sysnet.pe.kr/2/0/1565

.NET Framework: 428. .NET Reflection으로 다차원/Jagged 배열을 구분하는 방법
; https://www.sysnet.pe.kr/2/0/1653

.NET Framework: 537. C# - Reflection의 박싱 없이 값 형식을 다루는 방법
; https://www.sysnet.pe.kr/2/0/10866

.NET Framework: 685. C# - 구조체(값 형식)의 필드를 리플렉션을 이용해 값을 바꾸는 방법
; https://www.sysnet.pe.kr/2/0/11312

.NET Framework: 785. public으로 노출되지 않은 다른 어셈블리의 delegate 인스턴스를 Reflection으로 생성하는 방법
; https://www.sysnet.pe.kr/2/0/11583

.NET Framework: 842. .NET Reflection을 대체할 System.Reflection.Metadata 소개
; https://www.sysnet.pe.kr/2/0/11930

.NET Framework: 924. C# - Reflection으로 변경할 수 없는 readonly 정적 필드
; https://www.sysnet.pe.kr/2/0/12256

.NET Framework: 1045. C# - 런타임 시점에 이벤트 핸들러를 만들어 Reflection을 이용해 구독하는 방법
; https://www.sysnet.pe.kr/2/0/12609

.NET Framework: 1046. C# - 컴파일 시점에 참조할 수 없는 타입을 포함한 이벤트 핸들러를 Reflection을 이용해 구독하는 방법
; https://www.sysnet.pe.kr/2/0/12610

닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
; https://www.sysnet.pe.kr/2/0/13436

닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?
; https://www.sysnet.pe.kr/2/0/13608




C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능

오호~~~ 재미있는 글이 하나 있습니다. ^^

Accessing private members without reflection in C#
; https://www.meziantou.net/accessing-private-members-without-reflection-in-csharp.htm

기존에는 non public 멤버를 접근하려면 Reflection을 이용해야만 가능했는데요, .NET 8 런타임부터는 extern static 함수를 정의하는 것으로 해결할 수 있게 되었습니다.

예를 들어 볼까요? ^^ 다음과 같이 간단한 클래스를 DLL에 정의하고,

// C# 버전 및 런타임 버전에 무관하게 빌드 가능

public class Sample
{
    private Sample() { }
    internal Sample(int value) { }
}

위의 코드를 포함한 DLL을 참조한 콘솔 앱에서 다음과 같이 작성해 컴파일할 수 있습니다.

// C# 버전은 상관없으나, 런타임은 반드시 .NET 8+로 설정

using System.Runtime.CompilerServices;

namespace ConsoleApp1;

internal class Program
{
    [UnsafeAccessor(UnsafeAccessorKind.Constructor)]
    extern static Sample GetInstance();

    [UnsafeAccessor(UnsafeAccessorKind.Constructor)]
    extern static Sample GetInstance(int value);

    static void Main(string[] args)
    {
        var sample1 = GetInstance();
        var sample2 = GetInstance(1);

        Console.WriteLine(sample1 + " " + sample2); // 출력 결과: "Sample Sample"
    }
}

보는 바와 같이, "extern static" 예약어를 이용했기 때문에 P/Invoke에서와 같이 코드의 body를 포함하지 않아도 됩니다. 그리고 저 메서드는 "Sample" 타입을 반환하고 있으며, UnsafeAccessor 특성을 이용해 UnsafeAccessorKind.Constructor를 지정함으로써 "생성자"가 그 대상임을 알 수 있습니다.

위의 코드를 빌드하면 C# 컴파일러는 빈 body를 가진 GetInstance 메서드 항목만 생성해 놓습니다. 사실 이런 처리는 C# 12 컴파일러만의 동작은 아니고, 원래 "extern static"의 역할이 이제까지의 C# 컴파일러에서 그렇게 대우받았습니다.

그래서, 위의 코드를 .NET 7 런타임 이하에서 실행하면 다음과 같은 오류가 발생합니다.

Unhandled exception. System.TypeLoadException: Could not load type 'ConsoleApp1.Program' from assembly 'ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method 'GetInstance' has no implementation (no RVA).


반면, .NET 8 런타임 이상에서 실행하면 런타임 측에서 GetInstance 메서드가 UnsafeAccessor 특성을 가졌다는 것을 인지하고, 그것의 생성자를 연결하는 코드를 런타임에 생성해 연결해 줍니다.

어떤 원리인지 아시겠죠? ^^ 이렇게 실행 시 "정적"으로 연결되기 때문에 Reflection과는 달리 속도 저하 문제가 없어졌고, 특히 그동안 Native AOT 환경에서는 Reflection을 사용할 수 없었던 문제를 일부라도 우회하는 것이 가능해졌습니다.




위와 같은 동작에 기반해 "Accessing private members without reflection in C#" 글에 보면, 생성자뿐만 아니라 메서드, 프로퍼티, 필드에 대해 각각 instance/static 유형에 따라 어떻게 접근하는지를 보여주는 예제 코드가 나옵니다.

생성자의 호출 방식을 이해했다면 그냥 한번 쭉 살펴보는 것만으로 쉽게 이해할 수 있을 것입니다.

참고로, 아직 제네릭 타입에 대해서는 지원을 하지 않는다고 합니다. 또한, 근본적인 문제가 하나 더 있는데요, "타입의 멤버"가 아닌 "타입" 자체가 private인 경우에 대해서는 (어셈블리가 나뉜 경우) 위의 방법을 쓸 수 없습니다. 예를 들어, 위의 예제에서 "Sample" 타입이 "public"이 아니라면 "extern static Sample GetInstance();" 코드 자체가 "Sample" 식별자에 대해 "error CS0122: 'Sample' is inaccessible due to its protection level" 오류를 발생시킵니다.

바로 이 문제 때문에, 아래의 글에서 설명했던 코드를,

C# - Encoding.Default 값을 바꿀 수 있을까요?
; https://www.sysnet.pe.kr/2/0/12037

UnsafeAccessor로 대체할 수 없습니다. 현재 .NET 8에서는 Encoding.Default가 다음과 같은 식으로 구현되었는데요,

namespace System.Text
{
    public abstract partial class Encoding : ICloneable
    {
        // ...[생략]...

        private static readonly UTF8Encoding.UTF8EncodingSealed s_defaultEncoding = new UTF8Encoding.UTF8EncodingSealed(encoderShouldEmitUTF8Identifier: false);

        public static Encoding Default => s_defaultEncoding;

        // ...[생략]...
    }
}

위의 s_defaultEncoding에 대해 UnsafeAccessor를 이용하려면 다음과 같이 정의해야 하지만,

[UnsafeAccessor(UnsafeAccessorKind.StaticField, Name = "s_defaultEncoding")]
extern static ref UTF8Encoding.UTF8EncodingSealed GetDefaultEncoding(Encoding? @this);

UTF8Encoding.UTF8EncodingSealed 타입이 internal로 되어 있기 때문에 접근할 수 없어 빌드가 안 됩니다.

다행히, 이런 문제를 해결하기 위해 Proposal이 열려 있는데요,

[API Proposal]: UnsafeAccessorTypeAttribute for static or private type access
; https://github.com/dotnet/runtime/issues/90081

일단은 ".NET 9" 마일스톤 계획에 포함이 되긴 했습니다. 따라서 그때까진 타입 자체에 대해서는 여전히 reflection을 이용하거나, 아니면 그동안 단위 테스트에 종종 사용했던,

MSTest - 단위 테스트에 static/instance 유형의 private 멤버 접근 방법
; https://www.sysnet.pe.kr/2/0/12755

InternalsVisibleTo 특성을 활용해야 합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/13/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...
NoWriterDateCnt.TitleFile(s)
11273정성태8/22/201721624오류 유형: 415. 윈도우 업데이트 에러 Error 0x80070643
11272정성태8/21/201724745VS.NET IDE: 120. 비주얼 스튜디오 2017 버전 15.3.1 - C# 7.1 공개 [2]
11271정성태8/19/201719166VS.NET IDE: 119. Visual Studio 2017에서 .NET Core 2.0 프로젝트 환경 구성하는 방법
11270정성태8/17/201730606.NET Framework: 673. C#에서 enum을 boxing 없이 int로 변환하기 [2]
11269정성태8/17/201721414디버깅 기술: 93. windbg - 풀 덤프에서 .NET 스레드의 상태를 알아내는 방법
11268정성태8/14/201720991디버깅 기술: 92. windbg - C# Monitor Lock을 획득하고 있는 스레드 찾는 방법
11267정성태8/10/201725074.NET Framework: 672. 모노 개발 환경
11266정성태8/10/201724862.NET Framework: 671. C# 6.0 이상의 소스 코드를 Visual Studio 설치 없이 명령행에서 컴파일하는 방법
11265정성태8/10/201753124기타: 66. 도서: 시작하세요! C# 7.1 프로그래밍: 기본 문법부터 실전 예제까지 [11]
11264정성태8/9/201724000오류 유형: 414. UWP app을 signtool.exe로 서명 시 0x8007000b 오류 발생
11263정성태8/9/201719471오류 유형: 413. The C# project "..." is targeting ".NETFramework, Version=v4.0", which is not installed on this machine. [3]
11262정성태8/5/201718203오류 유형: 412. windbg - SOS does not support the current target architecture. [3]
11261정성태8/4/201720775디버깅 기술: 91. windbg - 풀 덤프 파일로부터 강력한 이름의 어셈블리 추출 후 사용하는 방법
11260정성태8/3/201718868.NET Framework: 670. C# - 실행 파일로부터 공개키를 추출하는 방법
11259정성태8/2/201718128.NET Framework: 669. 지연 서명된 어셈블리를 sn.exe -Vr 등록 없이 사용하는 방법
11258정성태8/1/201718892.NET Framework: 668. 지연 서명된 DLL과 서명된 DLL의 차이점파일 다운로드1
11257정성태7/31/201719128.NET Framework: 667. bypassTrustedAppStrongNames 옵션 설명파일 다운로드1
11256정성태7/25/201720580디버깅 기술: 90. windbg의 lm 명령으로 보이지 않는 .NET 4.0 ClassLibrary를 명시적으로 로드하는 방법 [1]
11255정성태7/18/201723161디버깅 기술: 89. Win32 Debug CRT Heap Internals의 0xBAADF00D 표시 재현 [1]파일 다운로드3
11254정성태7/17/201719475개발 환경 구성: 322. "Visual Studio Emulator for Android" 에뮬레이터를 "Android Studio"와 함께 쓰는 방법
11253정성태7/17/201719740Math: 21. "Coding the Matrix" 문제 2.5.1 풀이 [1]파일 다운로드1
11252정성태7/13/201718413오류 유형: 411. RTVS 또는 PTVS 실행 시 Could not load type 'Microsoft.VisualStudio.InteractiveWindow.Shell.IVsInteractiveWindowFactory2'
11251정성태7/13/201717062디버깅 기술: 88. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 (2)
11250정성태7/13/201720662디버깅 기술: 87. windbg 분석 - webengine4.dll의 MgdExplicitFlush에서 발생한 System.AccessViolationException의 crash 문제 [1]
11249정성태7/12/201718453오류 유형: 410. LoadLibrary("[...].dll") failed - The specified procedure could not be found.
11248정성태7/12/201724904오류 유형: 409. pip install pefile - 'cp949' codec can't decode byte 0xe2 in position 208687: illegal multibyte sequence
... [106]  107  108  109  110  111  112  113  114  115  116  117  118  119  120  ...