성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
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'>GetModuleHandleEx로 알아보는 .NET 메서드의 DLL 모듈 관계</h1> <p> 한국 마이크로소프트의 김명신 부장님이 번역하신 ^^ 책에서,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 제프리 리처의 Windows via C/C++ ; <a target='tab' href='http://www.yes24.com/24/Goods/3205340'>http://www.yes24.com/24/Goods/3205340</a> </pre> <br /> 아래의 GetModuleHandle / GetModuleHandleEx 코드를 봤습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { HMODULE hModule = <span style='color: blue; font-weight: bold'>GetModuleHandle</span>(NULL); wprintf(L"with GetModuleHandle(NULL) = 0x%x\r\n", hModule); wprintf(L"with __ImageBase = 0x%x\r\n", (HINSTANCE)&__ImageBase); hModule = NULL; <span style='color: blue; font-weight: bold'>GetModuleHandleEx</span>(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (PCTSTR)_tmain, &hModule); wprintf(L"with GetModuleHandleEx = 0x%x\r\n", hModule); return 0; } </pre> <br /> 이를 실행시키면 대충 다음과 같은 출력 결과를 얻습니다. (윈도우 8.1 + x86 타겟)<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > with GetModuleHandle(NULL) = 0xf80000 with __ImageBase = 0xf80000 with GetModuleHandleEx = 0xf80000 </pre> <br /> EXE 콘솔 실행 모듈에 담긴 코드에서 실행된 것이므로 모두 EXE 파일이 메모리에 로드된 주소(여기서는 0xf80000)를 가리키고 있습니다.<br /> <br /> 이 코드를 DLL에서 실행해 보면 어떨까요?<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > WIN32DLL_API void fnWin32Dll(void) { HMODULE hModule = GetModuleHandle(NULL); wprintf(L"with GetModuleHandle(NULL) = 0x%x\r\n", hModule); wprintf(L"with __ImageBase = 0x%x\r\n", (HINSTANCE)&__ImageBase); hModule = NULL; GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (PCTSTR)<span style='color: blue; font-weight: bold'>fnWin32Dll</span>, &hModule); wprintf(L"with GetModuleHandleEx = 0x%x\r\n", hModule); } </pre> <br /> GetModuleHandle(NULL)은 여전히 EXE 모듈의 로드 주소를 출력하는 반면 __ImageBase와 fnWin32Dll 함수 주소로 호출한 GetModuleHandleEx의 결과는 DLL 모듈의 로드 주소를 출력합니다. 대략 다음과 같습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > with GetModuleHandle(NULL) = 0xf80000 with __ImageBase = 0x56e90000 with GetModuleHandleEx = 0x56e90000 </pre> <br /> 디버깅 상태에서 "DEBUG" / "Windows" / "Modules" 메뉴(단축키: Ctrl + Alt + U)를 선택해 확인해 보면 실제로 해당 모듈들이 로드된 주소와 일치합니다.<br /> <br /> <img alt='get_module_handle_1.png' src='/SysWebRes/bbs/get_module_handle_1.png' /> <br /><br /> <hr style='width: 50%' /><br /> <br /> 문득 닷넷에서 이 함수들을 호출하면 어떻게 될까 궁금했습니다. 이론상으로 보면, 닷넷은 일단 GetModuleHandle(null)은 동일하게 EXE 파일의 로드 주소를 반환할 것입니다. 하지만, GetModuleHandleEx의 경우에는 모듈 주소를 찾지 못할 것입니다. 왜냐하면 JIT 컴파일될 것이므로 모듈 영역이 아닌 데이터 영역에서 코드로써 실행될 것이기 때문입니다.<br /> <br /> 실제로 한번 테스트를 해볼까요? ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // x86 타겟으로 빌드 using System; using System.Reflection; using System.Runtime.InteropServices; namespace CSharpConsole { class Program { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern IntPtr GetModuleHandle(string lpModuleName); [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] public static extern int GetModuleHandleEx(int dwFlags, int funcAddress, out IntPtr phModule); const int GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x4; static void Main(string[] args) { IntPtr pModule = GetModuleHandle(null); Console.WriteLine("GetModuleHandle(null) == 0x" + pModule.ToInt64().ToString("x")); //Action t = () => { }; //IntPtr tAddress = Marshal.GetFunctionPointerForDelegate(t); MethodInfo mainMethod = typeof(Program).GetMethod("Main", BindingFlags.Static | BindingFlags.NonPublic); OutputModuleAddress(mainMethod); } private static void OutputModuleAddress(MethodInfo mi) { IntPtr tAddress = mi.MethodHandle.GetFunctionPointer(); IntPtr pModule = IntPtr.Zero; int result = GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, tAddress.ToInt32(), out pModule); int lastError = Marshal.GetLastWin32Error(); if (lastError != 0 && lastError != 127) { Console.WriteLine(mi.Name + ": No Result(0x" + tAddress.ToInt32().ToString("x") + "), lastError = " + lastError + ", return = " + pModule.ToInt32().ToString("x")); return; } Console.WriteLine(mi.Name + " in 0x" + pModule.ToInt32().ToString("x")); } } } </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;' > GetModuleHandle(null) == 0xd40000 Main: No Result(0x1060050), lastError = 126, return = 0 </pre> <br /> 당연히 Modules 창을 통해 확인해 보면 Main 메서드의 0x1060050 위치에 해당하는 모듈이 없습니다.<br /> <br /> 그런데, 이 값이 나올 수 있는 조건이 하나 있습니다. 바로 NGen시켜 보관한 GAC의 모듈들입니다. 그것들은 이미 JIT 컴파일되어 모듈로 보관되어 있기 때문에 GetModuleHandleEx로도 구할 수 있습니다. 테스트를 위해 mscorlib.ni.dll에 있을 AppDomain.GetCurrentThreadId 메서드를 대상으로 코드를 작성하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > static void Main(string[] args) { // ...[생략]... MethodInfo getCurrentThreadIdMethod = typeof(AppDomain).GetMethod("GetCurrentThreadId", BindingFlags.Static | BindingFlags.Public); OutputModuleAddress(getCurrentThreadIdMethod); } </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;' > GetModuleHandle(null) == 0xb20000 Main: No Result(0xefc078), lastError = 126, return = 0 <span style='color: blue; font-weight: bold'>GetCurrentThreadId in 0x72cb0000</span> </pre> <br /> 이 시점에 Modules 창을 통해 확인하면 0x72cb0000에는 mscorlib.ni.dll이 있는 것을 확인할 수 있습니다.<br /> <br /> <img alt='get_module_handle_2.png' src='/SysWebRes/bbs/get_module_handle_2.png' /> <br /><br /> 그냥... 심심해서 ^^ 한번 테스트 해봤습니다.<br /> <br /> (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=878&boardid=331301885'>첨부 파일은 위의 테스트를 포함</a>합니다.)<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
6759
(왼쪽의 숫자를 입력해야 합니다.)