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

비밀번호

댓글 작성자
 




... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13122정성태8/26/20227398.NET Framework: 2045. C# 11 - 메서드 매개 변수에 대한 nameof 지원
13121정성태8/23/20225383C/C++: 157. Golang - 구조체의 slice 필드를 Reflection을 이용해 변경하는 방법
13120정성태8/19/20226847Windows: 209. Windows NT Service에서 UI를 다루는 방법 [3]
13119정성태8/18/20226396.NET Framework: 2044. .NET Core/5+ 프로젝트에서 참조 DLL이 보관된 공통 디렉터리를 지정하는 방법
13118정성태8/18/20225324.NET Framework: 2043. WPF Color의 기본 색 영역은 (sRGB가 아닌) scRGB [2]
13117정성태8/17/20227427.NET Framework: 2042. C# 11 - 파일 범위 내에서 유효한 타입 정의 (File-local types)파일 다운로드1
13116정성태8/4/20227878.NET Framework: 2041. C# - Socket.Close 시 Socket.Receive 메서드에서 예외가 발생하는 문제파일 다운로드1
13115정성태8/3/20228256.NET Framework: 2040. C# - ValueTask와 Task의 성능 비교 [1]파일 다운로드1
13114정성태8/2/20228386.NET Framework: 2039. C# - Task와 비교해 본 ValueTask 사용법파일 다운로드1
13113정성태7/31/20227628.NET Framework: 2038. C# 11 - Span 타입에 대한 패턴 매칭 (Pattern matching on ReadOnlySpan<char>)
13112정성태7/30/20228056.NET Framework: 2037. C# 11 - 목록 패턴(List patterns) [1]파일 다운로드1
13111정성태7/29/20227872.NET Framework: 2036. C# 11 - IntPtr/UIntPtr과 nint/nuint의 통합파일 다운로드1
13110정성태7/27/20227909.NET Framework: 2035. C# 11 - 새로운 연산자 ">>>" (Unsigned Right Shift)파일 다운로드1
13109정성태7/27/20229234VS.NET IDE: 177. 비주얼 스튜디오 2022를 이용한 (소스 코드가 없는) 닷넷 모듈 디버깅 - "외부 원본(External Sources)" [1]
13108정성태7/26/20227317Linux: 53. container에 실행 중인 Golang 프로세스를 디버깅하는 방법 [1]
13107정성태7/25/20226529Linux: 52. Debian/Ubuntu 계열의 docker container에서 자주 설치하게 되는 명령어
13106정성태7/24/20226162오류 유형: 819. 닷넷 6 프로젝트의 "Conditional compilation symbols" 기본값 오류
13105정성태7/23/20227464.NET Framework: 2034. .NET Core/5+ 환경에서 (프로젝트가 아닌) C# 코드 파일을 입력으로 컴파일하는 방법 - 두 번째 이야기 [1]
13104정성태7/23/202210530Linux: 51. WSL - init에서 systemd로 전환하는 방법
13103정성태7/22/20227115오류 유형: 818. WSL - systemd-genie와 관련한 2가지(systemd-remount-fs.service, multipathd.socket) 에러
13102정성태7/19/20226534.NET Framework: 2033. .NET Core/5+에서는 구할 수 없는 HttpRuntime.AppDomainAppId
13101정성태7/15/202215370도서: 시작하세요! C# 10 프로그래밍
13100정성태7/15/20227920.NET Framework: 2032. C# 11 - shift 연산자 재정의에 대한 제약 완화 (Relaxing Shift Operator)
13099정성태7/14/20227780.NET Framework: 2031. C# 11 - 사용자 정의 checked 연산자파일 다운로드1
13098정성태7/13/20226046개발 환경 구성: 647. Azure - scale-out 상태의 App Service에서 특정 인스턴스에 요청을 보내는 방법 [1]
13097정성태7/12/20225458오류 유형: 817. Golang - binary.Read: invalid type int32
... 16  17  18  19  [20]  21  22  23  24  25  26  27  28  29  30  ...