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

비밀번호

댓글 작성자
 




... 166  167  168  [169]  170  171  172  173  174  175  176  177  178  179  180  ...
NoWriterDateCnt.TitleFile(s)
797정성태11/9/200924622개발 환경 구성: 53. 물리 PC에 설치된 Windows 7을 Hyper-V로 이전하면?
796정성태11/2/200928467오류 유형: 89. Windows 7 백업 오류 - 0x80070057
795정성태11/2/200925850오류 유형: 88. TFS 2010 (beat2) 설치 오류 -TF255272
793정성태10/19/200927790.NET Framework: 166. WPF - XAML 요소의 네임스페이스와 CLR 타입 매핑
792정성태10/17/200928043웹: 13. IIS 7.5 에서 SQL Express 연결 시 오류
791정성태10/17/200931841웹: 12. 요청 페이지에 대해 빈 화면만 보이는 경우 [1]
789정성태10/13/200927490COM 개체 관련: 22. BB FlashBack SDK와 ActiveX 버전 관리 [7]
786정성태10/9/200923774개발 환경 구성: 52. 테스트를 위한 평가판 운영체제 구하기
785정성태10/8/200930433.NET Framework: 165. WPF - UI 업데이트를 바로 반영하고 싶다면? (2)파일 다운로드1
783정성태10/7/200928163.NET Framework: 164. WPF - 데이터 바인딩된 트리에서 부모 노드 찾는 방법 [1]파일 다운로드1
782정성태10/6/200930033개발 환경 구성: 51. Windows 7 - 다중 원격 접속(Remote Desktop) 허용
781정성태9/30/200927032.NET Framework: 163. WPF - TreeView 자동 스크롤 기능 해지 [2]파일 다운로드1
780정성태9/28/200931106Windows: 48. Windows 7/2008에서 ping을 위한 echo 요청 열기 [2]
779정성태9/24/200922453.NET Framework: 162. WPF - 중첩된 ScrollViewer의 크기 제어 - 두 번째 이야기파일 다운로드1
778정성태9/23/200923980오류 유형: 87. 시스템 시간 변경 후 Session이 맺어진 WCF 클라이언트의 예외 발생파일 다운로드1
776정성태9/17/200923074개발 환경 구성: 50. Reference assembly
775정성태9/13/200939827VC++: 37. XmlCodeGenerator를 C/C++ 코드 생성에 적용 [2]파일 다운로드1
773정성태9/5/200930391오류 유형 : 85. DEP 비호환 ActiveX 오류
772정성태9/2/200926953.NET Framework: 161. WPF - 윈도우 이벤트 가로채기 [1]파일 다운로드1
771정성태8/28/200921020.NET Framework: 160. WPF - 입력 포커스 외곽선 없애는 방법
770정성태8/26/200923395.NET Framework: 159. WCF - 같은 컴퓨터에서만 WCF 요청을 서비스하도록 설정
769정성태8/25/200926475개발 환경 구성: 49. GAC와 같은 Namespace Extension에 의해서 보여지는 폴더의 원본 확인 방법
768정성태8/24/200925834오류 유형: 85. WCF 연결 오류: MessageSecurityException
767정성태8/23/200934067.NET Framework: 158. 닷넷 프로파일러 - IL 코드 재작성 [14]
766정성태8/23/200934939.NET Framework: 157. C# 4.0 - dynamic 키워드 [4]파일 다운로드1
765정성태8/22/200928666.NET Framework: 156. XamDataGrid의 UnboundField 사용파일 다운로드1
... 166  167  168  [169]  170  171  172  173  174  175  176  177  178  179  180  ...