Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

(시리즈 글이 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# - 컴파일 시점에 참조할 수 없는 타입을 포함한 이벤트 핸들러를 Reflection을 이용해 구독하는 방법

지난 글에서 다룬 예제 코드에,

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

한 가지 상황을 더 가정해 보겠습니다. 그러니까, 여기서 만약 EventHandler의 TempEventArgs 타입을 .NET Framework 4.6.2부터 제공하는 EventSourceCreatedEventArgs 타입이라고 가정해 보겠습니다.

EventSourceCreatedEventArgs
; https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.tracing.eventsourcecreatedeventargs

public class MyTemp
{
    public void Create()
    {
        Created(this, new EventSourceCreatedEventArgs());
    }

    public event EventHandler<EventSourceCreatedEventArgs> Created;
}

그리고 저 이벤트를 구독해야 할 코드가 정의된 곳은 .NET 4.0 대상의 DLL 프로젝트라는 제약을 두겠습니다. 즉, 다음의 코드는 .NET 4.6.2 이상의 ConsoleApp1 EXE 프로젝트에 있고,

using System;
using System.Diagnostics.Tracing;

class Program
{
    static void Main(string[] args)
    {
        MyTemp instance = new MyTemp();

        ClassLibrary1.Class1 cl = new ClassLibrary1.Class1();
        cl.Subscribe(instance);

        instance.Create();
    }

}

public class MyTemp
{
    public void Create()
    {
        Created(this, new EventSourceCreatedEventArgs());
    }

    public event EventHandler<EventSourceCreatedEventArgs> Created;
}

Class1의 코드는 .NET 4.6.2 미만의 DLL 프로젝트에 놓여 있는 것입니다.

using System;
using System.Reflection;

// .NET 4.6.2 미만의 Framework을 대상으로 하는 프로젝트에서는 EventSourceCreatedEventArgs 참조 오류 발생

namespace ClassLibrary1
{
    public class Class1
    {
        public void Subscribe(object instance)
        {
            Type targetType = instance.GetType();
            Type arg2Type = typeof(EventSourceCreatedEventArgs);

            EventInfo ei = targetType.GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);
            ei.AddEventHandler(instance, (EventHandler<EventSourceCreatedEventArgs>)Instance_Created);
        }

        private static void Instance_Created(object sender, EventSourceCreatedEventArgs e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

그럼, 당연히 위의 코드에서 EventSourceCreatedEventArgs 타입은 정의되어 있지 않으므로 컴파일 오류가 발생합니다. 이럴 때는 EventSourceCreatedEventArgs 타입에 대한 모든 처리를 Reflection으로 제어해야 하는데요. 여기서 또 한가지 문제라면, 우리가 작성해야 할 EventHandler 조차도,

private static void Instance_Created(object sender, EventSourceCreatedEventArgs e)
{
    Console.WriteLine(e.ToString());
}

EventSourceCreatedEventArgs 타입에 대해 정적 바인딩을 하고 있으므로 역시나 사용할 수 없다는 점입니다. 그래서 이런 경우라면, 지난 글에 제시한 두 번째 방법을 이용해 동적으로 EventSourceCreatedEventArgs 타입에 대한 이벤트 핸들러 역할을 하는 메서드를 생성해야 합니다. 그렇긴 한데, 사실 DynamicMethod와 IL 코드의 조합으로 프로그래밍하는 것이 꽤나 귀찮은 작업이므로, 해당 이벤트 핸들러에 들어갈 코드를 C# 코드로 만든 EventArgs 타입의 인자를 갖는 이벤트 핸들러에 넣고 그 메서드를 동적 메서드에서 호출하도록 할 예정입니다. 즉, 다음과 같은 구조를 갖게 되는 것입니다.

public void Subscribe(object instance)
{
    Type targetType = instance.GetType();

    /* EventSourceCreatedEventArgs 타입 사용 불가
    Type arg2Type = typeof(EventSourceCreatedEventArgs);

    EventInfo ei = targetType.GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);
    ei.AddEventHandler(instance, (EventHandler<EventSourceCreatedEventArgs>)Proxy_Created);
    */

    // 동적으로 Proxy_Created 메서드를 만들고 이벤트 핸들러로 추가
}

/* 동적 생성
private static void Proxy_Created(object sender, EventSourceCreatedEventArgs e)
{
    Instance_Created(sender, e); // C#으로 만든 메서드로 호출 중계
}
*/

private static void Instance_Created(object sender, EventArgs e)
{
    Console.WriteLine(e.ToString());
}

이를 위해 Subscribe 코드를 다음과 같이 만들 수 있는데요,

using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;

namespace ClassLibrary1
{
    public class Class1
    {
        public void Subscribe(object instance)
        {
            Type targetType = instance.GetType();

            Type arg2Type;
            Assembly asm = TryGetType("System.Diagnostics.Tracing.EventWrittenEventArgs", out arg2Type);
            if (asm == null)
            {
                return;
            }

            EventInfo ei = targetType.GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);

            MethodInfo proxyMethodInfo = typeof(Class1).GetMethod("Instance_Created", BindingFlags.NonPublic | BindingFlags.Static);

            DynamicMethod proxyMethod = new DynamicMethod(
                "Proxy_Created",
                typeof(void), new Type[] { typeof(object), arg2Type });

            ILGenerator il = proxyMethod.GetILGenerator();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Call, proxyMethodInfo);
            il.Emit(OpCodes.Ret);

            // 아래의 코드에서 실행 시 System.ArgumentException 예외 발생
            Delegate proxyDelegate = proxyMethod.CreateDelegate(ei.EventHandlerType);
            ei.AddEventHandler(instance, proxyDelegate);
        }

        private static void Instance_Created(object sender, EventArgs e)
        {
            Console.WriteLine(e.ToString());
        }

        private Assembly TryGetType(string typeName, out Type targetType)
        {
            targetType = null;

            foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
            {
                Type type = asm.GetType(typeName);
                if (type != null)
                {
                    targetType = type;
                    return asm;
                }
            }

            return null;
        }
    }
}

재미있는 것은, 위의 코드를 실행하면 proxyMethod.CreateDelegate 호출에서 예외가 발생한다는 점입니다.

Unhandled Exception: System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
   at System.Delegate.CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
   at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType)
   at ClassLibrary1.Class1.Subscribe(Object instance)
   at Program.Main(String[] args)

오류 메시지를 보면, signature 또는 security transparency의 문제로 보이는데 해당 코드를 .NET Core에서 실행시켜 보면 이것이 signature 문제임을 알 수 있습니다.

// .NET Core 환경에서의 오류 메시지
System.ArgumentException
  HResult=0x80070057
  Message=Cannot bind to the target method because its signature is not compatible with that of the delegate type.
  Source=System.Private.CoreLib
  StackTrace:
   at System.Delegate.CreateDelegateNoSecurityCheck(Type type, Object target, RuntimeMethodHandle method)
   at System.Reflection.Emit.DynamicMethod.CreateDelegate(Type delegateType)
   at ClassLibrary1.Class1.Subscribe(Object instance)
   at Program.Main(String[] args)

이때의 ei.EventHandlerType 타입은 "System.EventHandler`1[System.Diagnostics.Tracing.EventSourceCreatedEventArgs]"인데, 개인적으로 왜 여기서 오류가 발생하는지 잘 모르겠습니다. (아시다시피 지난 예제에서는 위의 코드가 잘 동작했습니다.)

혹시 원인을 아시는 분은 덧글 부탁드립니다. ^^




이유는 알 수 없지만, 어떻게서든지 우회로를 찾아야 합니다. 이런 경우 한 가지 방법이 있다면, 어차피 모든 EventHandler의 인자가 System.EventArgs로부터 상속을 받기 때문에 동적 메서드의 인자를 System.Diagnostics.Tracing.EventWrittenEventArgs에서 EventArgs로 돌리는 것을 고려할 수 있습니다.

public void Subscribe(object instance)
{
    Type targetType = instance.GetType();

    Type arg2Type = typeof(System.EventArgs);

    EventInfo ei = targetType.GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);

    MethodInfo proxyMethodInfo = typeof(Class1).GetMethod("Instance_Created", BindingFlags.NonPublic | BindingFlags.Static);

    DynamicMethod proxyMethod = new DynamicMethod(
        "Proxy_Created",
        typeof(void), new Type[] { typeof(object), arg2Type });

    ILGenerator il = proxyMethod.GetILGenerator();

    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Ldarg_1);
    il.Emit(OpCodes.Call, proxyMethodInfo);
    il.Emit(OpCodes.Ret);

    Delegate proxyDelegate = proxyMethod.CreateDelegate(ei.EventHandlerType);
    ei.AddEventHandler(instance, proxyDelegate);
}

저렇게 바꾸면 일단 CreateDelegate 단계에서의 오류는 없어지지만, 대신 동적 생성 메서드 내에서의 "OpCodes.Call, proxyMethodInfo" 단계에서 (해당 이벤트가 발생한 실행 시점에) 다음과 같은 오류가 발생합니다.

Unhandled Exception: System.MethodAccessException: Attempt by method 'DynamicClass.Proxy_Created(System.Object, System.EventArgs)' to access method 'ClassLibrary1.Class1.Instance_Created(System.Object, System.EventArgs)' failed.
   at Proxy_Created(Object , EventArgs )
   at MyTemp.Create()
   at Program.Main(String[] args)

직접적인 원인은, 동적 생성한 메서드가 호출할 ClassLibrary1.Class1.Instance_Created의 접근 제한자가 "private"이기 때문에 발생하는 문제입니다. (그런데 여기서도 재미있는 점이 있다면, 위의 오류는 .NET Framework 환경에서만 발생하고 동일한 소스 코드를 .NET 5에서 실행하면 정상적으로 실행이 된다는 점입니다.)

어쨌든, .NET Framework에서도 동작하고 싶다면 ClassLibrary1.Class1.Instance_Created 메서드의 접근자를 public으로 명시하면 됩니다.

public void Subscribe(object instance)
{
    Type targetType = instance.GetType();

    Type arg2Type = typeof(System.EventArgs);

    EventInfo ei = targetType.GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);

    MethodInfo proxyMethodInfo = typeof(Class1).GetMethod("Instance_Created", BindingFlags.Public | BindingFlags.Static);

    DynamicMethod proxyMethod = new DynamicMethod(
        "Proxy_Created",
        typeof(void), new Type[] { typeof(object), arg2Type });

    ILGenerator il = proxyMethod.GetILGenerator();

    il.Emit(OpCodes.Ldarg_0);
    il.Emit(OpCodes.Ldarg_1);
    il.Emit(OpCodes.Call, proxyMethodInfo);
    il.Emit(OpCodes.Ret);

    Delegate proxyDelegate = proxyMethod.CreateDelegate(ei.EventHandlerType);
    ei.AddEventHandler(instance, proxyDelegate);
}

public static void Instance_Created(object sender, EventArgs e)
{
    Console.WriteLine("Instance_Created: " + e?.ToString());
}

휴~~~ 이제야 끝났군요. ^^ 실행해 보면 화면에 "Instance_Created: System.Diagnostics.Tracing.EventSourceCreatedEventArgs" 메시지가 출력되는 것을 확인할 수 있습니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




그나저나, 기왕에 EventArgs 인자를 담고 있는 메서드를 사용할 예정이라면 굳이 저렇게 중간에 동적 메서드(Proxy_Created)를 끼지 않고 Instance_Created 이벤트 핸들러를 바로 구독하는 것도 가능할지 모릅니다.

그래서 본문의 예제를 DynamicMethod 생성 없이 곧바로 다음과 같이 Instance_Created 메서드를 이벤트 핸들러에 추가하면,

EventInfo ei = targetType.GetEvent("Created", BindingFlags.Public | BindingFlags.Instance);
ei.AddEventHandler(instance, (EventHandler<EventArgs>)Instance_Created);

// 또는,

MethodInfo miAdd = ei.GetAddMethod();
miAdd.Invoke(instance, new object[] { (EventHandler<EventArgs>)Instance_Created });

아쉽게도 이번에는 형변환을 할 수 없다는 오류가 발생합니다.

Unhandled Exception: System.ArgumentException: Object of type 'System.EventHandler`1[System.EventArgs]' cannot be converted to type 'System.EventHandler`1[System.Diagnostics.Tracing.EventSourceCreatedEventArgs]'.
   at System.RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
   at System.Reflection.MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.EventInfo.AddEventHandler(Object target, Delegate handler)
   at ClassLibrary1.Class1.Subscribe(Object instance)
   at Program.Main(String[] args)

어쩔 수 없습니다. ^^ 동적 메서드를 만들어 중계해야 합니다.




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







[최초 등록일: ]
[최종 수정일: 2/27/2023]

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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...
NoWriterDateCnt.TitleFile(s)
12564정성태3/16/20217129VS.NET IDE: 160. 새 프로젝트 창에 C++/CLI 프로젝트 템플릿이 없는 경우
12563정성태3/16/20219108개발 환경 구성: 551. C# - JIRA REST API 사용 정리 (3) jira-oauth-cli 도구를 이용한 키 관리
12562정성태3/15/202110269개발 환경 구성: 550. C# - JIRA REST API 사용 정리 (2) JIRA OAuth 토큰으로 API 사용하는 방법파일 다운로드1
12561정성태3/12/20218879VS.NET IDE: 159. Visual Studio에서 개행(\n, \r) 등의 제어 문자를 치환하는 방법 - 정규 표현식 사용
12560정성태3/11/202110174개발 환경 구성: 549. ssh-keygen으로 생성한 개인키/공개키 파일을 각각 PKCS8/PEM 형식으로 변환하는 방법
12559정성태3/11/20219633.NET Framework: 1028. 닷넷 5 환경의 Web API에 OpenAPI 적용을 위한 NSwag 또는 Swashbuckle 패키지 사용 [2]파일 다운로드1
12558정성태3/10/20219112Windows: 192. Power Automate Desktop (Preview) 소개 - Bitvise SSH Client 제어 [1]
12557정성태3/10/20217769Windows: 191. 탐색기의 보안 탭에 있는 "Object name" 경로에 LEFT-TO-RIGHT EMBEDDING 제어 문자가 포함되는 문제
12556정성태3/9/20217028오류 유형: 703. PowerShell ISE의 Debug / Toggle Breakpoint 메뉴가 비활성 상태인 경우
12555정성태3/8/20219078Windows: 190. C# - 레지스트리에 등록된 DigitalProductId로부터 라이선스 키(Product Key)를 알아내는 방법파일 다운로드2
12554정성태3/8/20218883.NET Framework: 1027. 닷넷 응용 프로그램을 위한 PDB 옵션 - full, pdbonly, portable, embedded
12553정성태3/5/20219338개발 환경 구성: 548. 기존 .NET Framework 프로젝트를 .NET Core/5+ 용으로 변환해 주는 upgrade-assistant, try-convert 도구 소개 [4]
12552정성태3/5/20218592개발 환경 구성: 547. github workflow/actions에서 Visual Studio Marketplace 패키지 등록하는 방법
12551정성태3/5/20217498오류 유형: 702. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly. (2)
12550정성태3/5/20217186오류 유형: 701. Live Share 1.0.3713.0 버전을 1.0.3884.0으로 업데이트 이후 ContactServiceModelPackage 오류 발생하는 문제
12549정성태3/4/20217719오류 유형: 700. VsixPublisher를 이용한 등록 시 다양한 오류 유형 해결책
12548정성태3/4/20218503개발 환경 구성: 546. github workflow/actions에서 nuget 패키지 등록하는 방법
12547정성태3/3/20219005오류 유형: 699. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly.
12546정성태3/3/20218619개발 환경 구성: 545. github workflow/actions에서 빌드시 snk 파일 다루는 방법 - Encrypted secrets
12545정성태3/2/202111359.NET Framework: 1026. 닷넷 5에 추가된 POH (Pinned Object Heap) [10]
12544정성태2/26/202111563.NET Framework: 1025. C# - Control의 Invalidate, Update, Refresh 차이점 [2]
12543정성태2/26/20219889VS.NET IDE: 158. C# - 디자인 타임(design-time)과 런타임(runtime)의 코드 실행 구분
12542정성태2/20/202112225개발 환경 구성: 544. github repo의 Release 활성화 및 Actions를 이용한 자동화 방법 [1]
12541정성태2/18/20219494개발 환경 구성: 543. 애저듣보잡 - Github Workflow/Actions 소개
12540정성태2/17/20219837.NET Framework: 1024. C# - Win32 API에 대한 P/Invoke를 대신하는 Microsoft.Windows.CsWin32 패키지
12539정성태2/16/20219747Windows: 189. WM_TIMER의 동작 방식 개요파일 다운로드1
... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...