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)
13297정성태3/26/20234350Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233693Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20233957Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234126.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234196오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234326Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234735.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234241.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233435Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233550Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233703Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234162Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233754Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20233955Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233495오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233819Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233721Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234474개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/20234013오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/20233974개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/20234637개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/20234318.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어
13275정성태3/3/20234676.NET Framework: 2101. C# 11의 ref 필드 설명
13274정성태3/2/20234260.NET Framework: 2100. C# - ref 필드로 ref struct 타입을 허용하지 않는 이유
13273정성태2/28/20233958.NET Framework: 2099. C# - 관리 포인터로서의 ref 예약어 의미
13272정성태2/27/20234217오류 유형: 850. SSMS - mdf 파일을 Attach 시킬 때 Operating system error 5: "5(Access is denied.)" 에러
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...