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

(시리즈 글이 10개 있습니다.)
.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




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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13597정성태4/15/2024278닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024506닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024490닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024700닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/2024915닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241185C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241152닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241067Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241131닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241184닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241131오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241258Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241087Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241042개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241143Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241217Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241362개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241131닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241619닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241850닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241539닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241661닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241551닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241560닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...