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)
12714정성태7/16/20218257오류 유형: 735. VCRUNTIME140.dll, MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll이 없어 exe 실행이 안 되는 경우
12713정성태7/16/20218784.NET Framework: 1077. C# - 동기 방식이면서 비동기 규약을 따르게 만드는 Task.FromResult파일 다운로드1
12712정성태7/15/20218221개발 환경 구성: 579. Azure - 리눅스 호스팅의 Site Extension 제작 방법
12711정성태7/15/20218582개발 환경 구성: 578. Azure - Java Web App Service를 위한 Site Extension 제작 방법
12710정성태7/15/202110369개발 환경 구성: 577. MQTT - emqx.io 서비스 소개
12709정성태7/14/20216962Linux: 42. 실행 중인 docker 컨테이너에 대한 구동 시점의 docker run 명령어를 확인하는 방법
12708정성태7/14/202110366Linux: 41. 리눅스 환경에서 디스크 용량 부족 시 원인 분석 방법
12707정성태7/14/202177632오류 유형: 734. MySQL - Authentication method 'caching_sha2_password' not supported by any of the available plugins.
12706정성태7/14/20218811.NET Framework: 1076. C# - AsyncLocal 기능을 CallContext만으로 구현하는 방법 [2]파일 다운로드1
12705정성태7/13/20218982VS.NET IDE: 168. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 - 두 번째 이야기
12704정성태7/12/20218131개발 환경 구성: 576. Azure VM의 서비스를 Azure Web App Service에서만 접근하도록 NSG 설정을 제한하는 방법
12703정성태7/11/202113775개발 환경 구성: 575. Azure VM에 (ICMP) ping을 허용하는 방법
12702정성태7/11/20218896오류 유형: 733. TaskScheduler에 등록된 wacs.exe의 Let's Encrypt 인증서 업데이트 문제
12701정성태7/9/20218570.NET Framework: 1075. C# - ThreadPool의 스레드는 반환 시 ThreadStatic과 AsyncLocal 값이 초기화 될까요?파일 다운로드1
12700정성태7/8/20218960.NET Framework: 1074. RuntimeType의 메모리 누수? [1]
12699정성태7/8/20217754VS.NET IDE: 167. Visual Studio 디버깅 중 GC Heap 상태를 보여주는 "Show Diagnostic Tools" 메뉴 사용법
12698정성태7/7/202111702오류 유형: 732. Windows 11 업데이트 시 3% 또는 0%에서 다운로드가 멈춘 경우
12697정성태7/7/20217576개발 환경 구성: 574. Windows 11 (Insider Preview) 설치하는 방법
12696정성태7/6/20218169VC++: 146. 운영체제의 스레드 문맥 교환(Context Switch)을 유사하게 구현하는 방법파일 다운로드2
12695정성태7/3/20218206VC++: 145. C 언어의 setjmp/longjmp 기능을 Thread Context를 이용해 유사하게 구현하는 방법파일 다운로드1
12694정성태7/2/202110181Java: 24. Azure - Spring Boot 앱을 Java SE(Embedded Web Server)로 호스팅 시 로그 파일 남기는 방법 [1]
12693정성태6/30/20217927오류 유형: 731. Azure Web App Site Extension - Failed to install web app extension [...]. {1}
12692정성태6/30/20217803디버깅 기술: 180. Azure - Web App의 비정상 종료 시 남겨지는 로그 확인
12691정성태6/30/20218616개발 환경 구성: 573. 테스트 용도이지만 테스트에 적합하지 않은 Azure D1 공유(shared) 요금제
12690정성태6/28/20219450Java: 23. Azure - 자바(Java)로 만드는 Web App Service - Tomcat 호스팅
12689정성태6/25/202110037오류 유형: 730. Windows Forms 디자이너 - The class Form1 can be designed, but is not the first class in the file. [1]
... 31  32  33  34  35  36  [37]  38  39  40  41  42  43  44  45  ...