성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Java - How to use the Foreign Funct...
[정성태] 제가 큰 실수를 했군요. ^^; Delegate를 통한 Bein...
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>AllowPartiallyTrustedCallers 특성이 적용된 GAC 어셈블리에서 DynamicMethod의 calli 명령어 사용</h1> <p> calli 명령어 사용법에 대해 지난 글에서 대략 설명드렸는데요.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > calli IL 호출이 DllImport 호출보다 빠를까요? ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/10808'>http://www.sysnet.pe.kr/2/0/10808</a> OpenCover 코드 커버리지 도구의 동작방식을 통해 살펴보는 Calli IL 코드 사용법 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/2882'>http://www.sysnet.pe.kr/2/0/2882</a> </pre> <br /> calli IL 코드를 사용하는 메서드를 만들기 위해 직접 DynamicMethod를 사용했습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // x86 기준 calli IL 코드를 사용하는 동적 메서드 생성 long result = 0; if (IntPtr.Size == 4) { result = GetThisThreadId32(); } var type = typeof(Class1); DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, type, true); var iLGenerator = dynamicMethod.GetILGenerator(); if (IntPtr.Size == 4) { iLGenerator.Emit(OpCodes.Ldc_I4, (int)result); } iLGenerator.<span style='color: blue; font-weight: bold'>EmitCalli(OpCodes.Calli,</span> CallingConvention.StdCall, typeof(int), Type.EmptyTypes); iLGenerator.Emit(OpCodes.Ret); GetThisThreadIdDelegate tempDelegate = dynamicMethod.CreateDelegate(typeof(GetThisThreadIdDelegate)) as GetThisThreadIdDelegate; _GetThisThreadIdMethod = tempDelegate; </pre> <br /> 재미있는 것은 이 코드를 .NET 4.0 보안의 APTCA가 적용된 어셈블리 내에 두면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > .NET CLR4 보안 모델 - 3. CLR4 보안 모델에서의 APTCA 역할 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/1682'>http://www.sysnet.pe.kr/2/0/1682</a> </pre> <br /> dynamicMethod.CreateDelegate 단계까지 정상적으로 실행은 되지만 그렇게 해서 생성한 _GetThisThreadIdMethod 메서드를 호출하면 다음과 같은 예외가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > <span style='color: blue; font-weight: bold'>System.Security.VerificationException was caught</span> _HResult=-2146233075 _message=Operation could destabilize the runtime. HResult=-2146233075 IsTransient=false Message=<span style='color: blue; font-weight: bold'>Operation could destabilize the runtime.</span> Source=ClassLibrary1 StackTrace: at () at ClassLibrary1.Class1.GetThisThreadId() InnerException: </pre> <br /> 원인은 DynamicMethod 메서드의 추가를 APTCA가 적용된 어셈블리 내에 있는 타입을 기준으로 했기 때문입니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > var type = typeof(<span style='color: blue; font-weight: bold'>Class1</span>); DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, type, true); </pre> <br /> 따라서, 해당 타입 대신 APTCA가 적용되지 않은 어셈블리에 정의된 타입을 대신 넣어주면 됩니다. 가령, 이런 식이겠지요.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // GAC 어셈블리의 GetThisThreadId를 호출할 때 별도의 타입을 지정 class Program { static void Main(string[] args) { ClassLibrary1.Class1.GetThisThreadId(<span style='color: blue; font-weight: bold'>typeof(Program)</span>); } } </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // ClassLibrary1.Class1.GetThisThreadId 에서는 외부의 타입을 기반으로 동적 메서드 추가 using System; using System.Reflection.Emit; using System.Runtime.InteropServices; namespace ClassLibrary1 { [System.Security.SecuritySafeCritical] public class Class1 { // ...[생략]... public static int GetThisThreadId(<span style='color: blue; font-weight: bold'>Type type</span>) { long result = 0; // ...[생략]... DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, <span style='color: blue; font-weight: bold'>type</span>, true); // ...[생략]... GetThisThreadIdDelegate tempDelegate = dynamicMethod.CreateDelegate(typeof(GetThisThreadIdDelegate)) as GetThisThreadIdDelegate; _GetThisThreadIdMethod = tempDelegate; return _GetThisThreadIdMethod(); } } } </pre> <br /> 근데... 이런 식은 좀 번거로우니 의존성을 제거하기 위해 아예 어셈블리 및 타입도 동적으로 생성해 주는 방법이 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > AssemblyName myAssemblyName = new AssemblyName(); myAssemblyName.Name = "EmittedAssembly_" + Guid.NewGuid().ToString(); AssemblyBuilder myAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(myAssemblyName, AssemblyBuilderAccess.Run); ModuleBuilder myModule = myAssembly.DefineDynamicModule("EmittedModule"); TypeBuilder helperClass = myModule.DefineType("Helper", TypeAttributes.Public); <span style='color: blue; font-weight: bold'>Type type = helperClass.CreateType();</span> DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, <span style='color: blue; font-weight: bold'>type</span>, true); </pre> <br /> 어떤 것을 사용하든... 취향에 맞게! ^^<br /> <br /> (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=933&boardid=331301885'>첨부한 파일은 위의 예제 코드를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
7487
(왼쪽의 숫자를 입력해야 합니다.)