Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

GetFunctionPointer 호출 시 System.InvalidProgramException 예외 발생

현상은 간단합니다. 제네릭 메서드인 경우 그에 대해 GetFunctionPointer를 호출하면,

using System;
using System.Reflection;
using System.Threading;

public class Program
{
    public static void GenericMethod<T>(T obj)
    {
        Thread.Sleep(1);
    }

    static unsafe void Main()
    {
        Type type = typeof(Program);
        MethodInfo mi = type.GetMethod("GenericMethod", BindingFlags.Static | BindingFlags.Public);
        {
            string fullName = string.Format("{0}.{1}", type.FullName, mi.Name);
            IntPtr methodBody = mi.MethodHandle.GetFunctionPointer(); // 예외 발생
            Console.WriteLine(fullName);
        }
    }
}

MethodInfo.MethodHandle.GetFunctionPointer 메서드 호출에서 다음과 같은 예외가 발생합니다.

An unhandled exception of type 'System.InvalidProgramException' occurred in mscorlib.dll

Additional information: Common Language Runtime detected an invalid program.

이게... 이상한 듯 하면서도 사실 당연한 겁니다. 왜냐하면, 제네릭인 경우 컴파일러가 생성한 IL 단계에는 제네릭의 타입이 정해지지 않은 상태이고, 실제 메서드가 사용될 때 기계어 컴파일이 타입에 따라 확장되면서 컴파일되기 때문에 GenericMethod 자체의 FunctionPointer 값을 대표할 수 없는 것입니다. 가령 그 값이 0x00100으로 반환되었다고 해도 GenericMethod<int>(int obj)로 확장된 메서드의 FunctionPointer는 또 다른 값이 될 수 있는 것입니다.

그래서, 원래는 제네릭 메서드의 제대로 된 FunctionPointer를 구하고 싶다면 다음과 같이 해줘야 합니다.

MethodInfo mi = type.GetMethod("GenericMethod", BindingFlags.Static | BindingFlags.Public);
MethodInfo intMethod = mi.MakeGenericMethod(typeof(int));

string fullName = string.Format("{0}.{1}", type.FullName, intMethod.Name);
IntPtr methodBody = intMethod.MethodHandle.GetFunctionPointer();
Console.WriteLine(fullName); // Program.GenericMethod

그런데, 재미있는 것은 클래스 수준의 제네릭 인자가 있는 것은 또 잘됩니다.

public class GenericClass<T>
{
    public static void Test(T arg)
    {
        Console.WriteLine(arg);
    }
}

type = typeof(GenericClass<>);
mi = type.GetMethod("Test", BindingFlags.Static | BindingFlags.Public);
{
    string fullName = string.Format("{0}.{1}", type.FullName, mi.Name);
    IntPtr methodBody = mi.MethodHandle.GetFunctionPointer();
    Console.WriteLine(fullName); // GenericClass`1.Test
}




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/17/2021]

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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  [54]  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12276정성태7/23/202010044.NET Framework: 930. 개발자를 위한 닷넷 어셈블리 바인딩 - DEVPATH 환경 변수
12275정성태7/22/202012593개발 환경 구성: 497. 닷넷에서 접근해보는 InterSystems의 IRIS Data Platform 데이터베이스파일 다운로드1
12274정성태7/21/202011967개발 환경 구성: 496. Azure - Blob Storage Account의 Location 이전 방법 [1]파일 다운로드1
12273정성태7/18/202013608개발 환경 구성: 495. Azure - Location이 다른 웹/DB 서버의 경우 발생하는 성능 하락
12272정성태7/16/20208618.NET Framework: 929. (StrongName의 버전 구분이 필요 없는) .NET Core 어셈블리 바인딩 규칙 [2]파일 다운로드1
12271정성태7/16/202010667.NET Framework: 928. .NET Framework의 Strong-named 어셈블리 바인딩 (2) - 런타임에 바인딩 리디렉션파일 다운로드1
12270정성태7/16/202011478오류 유형: 633. SSL_CTX_use_certificate_file - error:140AB18F:SSL routines:SSL_CTX_use_certificate:ee key too small
12269정성태7/16/20208514오류 유형: 632. .NET Core 웹 응용 프로그램 - The process was terminated due to an unhandled exception.
12268정성태7/15/202010662오류 유형: 631. .NET Core 웹 응용 프로그램 오류 - HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process
12267정성태7/15/202012334.NET Framework: 927. C# - 윈도우 프로그램에서 Credential Manager를 이용한 보안 정보 저장파일 다운로드1
12266정성태7/14/202010018오류 유형: 630. 사용자 계정을 지정해 CreateService API로 서비스를 등록한 경우 "Error 1069: The service did not start due to a logon failure." 오류발생
12265정성태7/10/20209184오류 유형: 629. Visual Studio - 웹 애플리케이션 실행 시 "Unable to connect to web server 'IIS Express'." 오류 발생
12264정성태7/9/202018177오류 유형: 628. docker: Error response from daemon: Conflict. The container name "..." is already in use by container "...".
12261정성태7/9/202011135VS.NET IDE: 148. 윈도우 10에서 .NET Core 응용 프로그램을 리눅스 환경에서 실행하는 2가지 방법 - docker, WSL 2 [5]
12260정성태7/8/20209568.NET Framework: 926. C# - ETW를 이용한 ThreadPool 스레드 감시파일 다운로드1
12259정성태7/8/20209087오류 유형: 627. nvlddmkm.sys의 BAD_POOL_HEADER BSOD 문제 [1]
12258정성태7/8/202012259기타: 77. DataDog APM 간략 소개
12257정성태7/7/20209279.NET Framework: 925. C# - ETW를 이용한 Monitor Enter/Exit 감시파일 다운로드1
12256정성태7/7/20209697.NET Framework: 924. C# - Reflection으로 변경할 수 없는 readonly 정적 필드 [4]
12255정성태7/6/202010105.NET Framework: 923. C# - ETW(Event Tracing for Windows)를 이용한 Finalizer 실행 감시파일 다운로드1
12254정성태7/2/20209974오류 유형: 626. git - REMOTE HOST IDENTIFICATION HAS CHANGED!
12253정성태7/2/202011026.NET Framework: 922. C# - .NET ThreadPool의 Local/Global Queue파일 다운로드1
12252정성태7/2/202013017.NET Framework: 921. C# - I/O 스레드를 사용한 비동기 소켓 서버/클라이언트파일 다운로드2
12251정성태7/1/202010976.NET Framework: 920. C# - 파일의 비동기 처리 유무에 따른 스레드 상황 [1]파일 다운로드2
12250정성태6/30/202013628.NET Framework: 919. C# - 닷넷에서의 진정한 비동기 호출을 가능케 하는 I/O 스레드 사용법 [1]파일 다운로드1
12249정성태6/29/20209763오류 유형: 625. Microsoft SQL Server 2019 RC1 Setup - 설치 제거 시 Warning 26003 오류 발생
... 46  47  48  49  50  51  52  53  [54]  55  56  57  58  59  60  ...