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

비밀번호

댓글 작성자
 




... 181  182  183  184  185  [186]  187  188  189  190  191  192  193  194  195  ...
NoWriterDateCnt.TitleFile(s)
429정성태12/31/200632587    답변글 개발 환경 구성: 18.11. 서비스를 위한 인증서 설치
352정성태10/2/200622232개발 환경 구성: 17. VPC에 Linux 설치하는 방법 [1]
351정성태10/8/200624688개발 환경 구성: 16. 성태의 무식한(!) 리눅스 탐방기. [4]
349정성태9/26/200623308디버깅 기술: 10. C++/CLI에서 제공되는 명시적인 파괴자의 비밀
347정성태10/6/200627263디버깅 기술: 9. .NET IDisposable 처리 정리 [1]
346정성태9/23/200620617개발 환경 구성: 15. 툴박스에 컨트롤이 자동으로 나타나도록 해주는 옵션 설정
345정성태9/20/200619823오류 유형: 12. WCF 오류 메시지 - Error while trying to reflect on attribute 'MessageContractAttribute'
343정성태10/18/200631733개발 환경 구성: 14. SandCastle 사용법 (NDoc을 대체하는 문서화 도구) [1]파일 다운로드1
344정성태9/20/200621895    답변글 개발 환경 구성: 14.1. 오류 유형 - GAC 에 등록된 DLL 에 대한 문서화 시 오류
340정성태9/15/200621174개발 환경 구성: 13. ISO 파일을 가상 CD-ROM으로 매핑해주는 프로그램
339정성태9/14/200620632오류 유형: 11. ProtocolsSection?
338정성태2/4/200728798개발 환경 구성: 12. BUG: 웹 서비스에서 DataTable 사용하기 [2]파일 다운로드1
350정성태10/2/200622084    답변글 개발 환경 구성: 12.1. ASMX 2.0 and SchemaImporterExtensions파일 다운로드1
335정성태8/20/200629725디버깅 기술: 8. COM+ 서버 응용 프로그램에 대한 F5 디버깅 방법
334정성태8/20/200624974디버깅 기술: 7. VS.NET 2003/2005의 다중 프로젝트 디버깅
333정성태8/20/200625414개발 환경 구성: 11. COM+ 서버 활성화 보안 설정
331정성태8/27/200618349개발 환경 구성: 10. 최대 절전 모드와 VPC 네트워크 문제
330정성태8/20/200618697개발 환경 구성: 9. VPC로 구성하는 개인 환경
328정성태8/20/200636543개발 환경 구성: 8. AppVerifier 사용법 [1]
327정성태8/16/200633372개발 환경 구성: 7. ActiveX 서명 과정 자동화 [1]
326정성태8/16/200627206Team Foundation Server: 13. Sysnet 웹 사이트 TFS Migration
322정성태8/15/200622009개발 환경 구성: 6. 4GB 메모리 구성 [1]
316정성태9/20/200641281디버깅 기술: 6. .NET 예외 처리 정리 [6]
309정성태12/27/200642059디버깅 기술: 5. PDB 이야기 [7]
310정성태8/5/200629032    답변글 디버깅 기술: 5.1. PDB 파일에 따른 Debug 정보 - WinForm + Library 유형의 프로젝트파일 다운로드1
311정성태8/10/200628650    답변글 디버깅 기술: 5.2. PDB 파일에 따른 Debug 정보 - .NET 2.0 Web Application Project + Library 유형의 프로젝트
... 181  182  183  184  185  [186]  187  188  189  190  191  192  193  194  195  ...