성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Working with Rust Libraries from C#...
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
글쓰기
제목
이름
암호
전자우편
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'>C++ 생성자를 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;' > C++ DLL로 class를 export후 LoadLibrary로 DLL을 불러와 new로 class 객체를 생성할 수 있는 방법 없을까요 ; <a target='tab' href='http://lab.gamecodi.com/board/zboard.php?id=GAMECODILAB_QnA_etc&no=3843&z='>http://lab.gamecodi.com/board/zboard.php?id=GAMECODILAB_QnA_etc&no=3843&z=</a> </pre> <br /> 질문의 요지는 이렇습니다. C++ 클래스를 DLL에 구현해 두었는데, 이 클래스의 인스턴스를 외부 EXE/DLL에서 접근해 생성하고 싶다는 것입니다. 검색해 보면 이를 위한 방법을 다음의 글에서 찾을 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Using classes exported from a DLL using LoadLibrary ; <a target='tab' href='http://www.codeproject.com/Articles/9405/Using-classes-exported-from-a-DLL-using-LoadLibrar'>http://www.codeproject.com/Articles/9405/Using-classes-exported-from-a-DLL-using-LoadLibrar</a> </pre> <br /> 직접 실습을 해볼까요? ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 우선, Visual Studio에서 C++ Win32 DLL 프로젝트를 "Export symbols" 옵션을 켜서 생성한 후, 기본 포함된 CWin32Project1 클래스의 코드에 다음과 같이 테스트를 위해 필드 n과 Print 함수를 포함시켜 둡니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > #define WIN32PROJECT1_API __declspec(dllexport) #include <stdio.h> class WIN32PROJECT1_API CWin32Project1 { public: <span style='color: blue; font-weight: bold'>int n;</span> CWin32Project1(void); <span style='color: blue; font-weight: bold'> void Print() { printf("%d\r\n", n); }</span> }; CWin32Project1::CWin32Project1() { <span style='color: blue; font-weight: bold'>n = 500;</span> return; } </pre> <br /> 컴파일하고 Visual Studio 명령 프롬프트를 실행시켜 dumpbin.exe를 실행하면 생성자가 export된 심볼을 구할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C:\temp\Win32Project1\x64\Debug><span style='color: blue; font-weight: bold'>dumpbin /exports</span> Win32Project1.dll Microsoft (R) COFF/PE Dumper Version 14.00.23026.0 Copyright (C) Microsoft Corporation. All rights reserved. Dump of file Win32Project1.dll File Type: DLL Section contains the following exports for Win32Project1.dll 00000000 characteristics 55FAAD26 time date stamp Thu Sep 17 21:08:06 2015 0.00 version 1 ordinal base 6 number of functions 6 number of names ordinal hint RVA name 1 0 0001100A <span style='color: blue; font-weight: bold'>??0CWin32Project1@@QEAA@XZ</span> = @ILT+5(??0CWin32Project1@@QEAA@XZ) 2 1 00011069 ??4CWin32Project1@@QEAAAEAV0@$$QEAV0@@Z = @ILT+100(??4CWin32Project1@@QEAAAEAV0@$$QEAV0@@Z) 3 2 000111B8 ??4CWin32Project1@@QEAAAEAV0@AEBV0@@Z = @ILT+435(??4CWin32Project1@@QEAAAEAV0@AEBV0@@Z) 4 3 000112B2 <span style='color: blue; font-weight: bold'>?Print@CWin32Project1@@QEAAXXZ</span> = @ILT+685(?Print@CWin32Project1@@QEAAXXZ) 5 4 000112CB ?fnWin32Project1@@YAHXZ = @ILT+710(?fnWin32Project1@@YAHXZ) 6 5 0001C164 ?nWin32Project1@@3HA = ?nWin32Project1@@3HA (int nWin32Project1) Summary 1000 .00cfg 1000 .data 1000 .idata 1000 .pdata 3000 .rdata 1000 .reloc 1000 .rsrc 8000 .text 10000 .textbss </pre> <br /> 이 값을 이용해 LoadLibrary/GetProcAddress로 함수 포인터를 구하는 코드는 이렇습니다.<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" #include <Windows.h> class CWin32Project1 { public: int n; CWin32Project1(void); void Print(); }; typedef void(*CTORFUNC) (void *pThis); typedef void(*PRINTFUNC) (void *pThis); int main() { HMODULE hModule = ::LoadLibrary(L"Win32Project1.dll"); if (hModule == NULL) { printf("NOT FOUND: Module\r\n"); return 1; } // <a target='tab' href='https://devblogs.microsoft.com/oldnewthing/20040112-00/?p=41083'>Why can't I GetProcAddress a function I dllexport'ed?</a> // 64비트와 32비트에서의 export symbol 이름이 다르다는 점! #if defined(_AMD64_) char *ctorName = "??0CWin32Project1@@QEAA@XZ"; char *printName = "?Print@CWin32Project1@@QEAAXXZ"; #else char *ctorName = "??0CWin32Project1@@QAE@XZ"; char *printName = "?Print@CWin32Project1@@QAEXXZ"; #endif CTORFUNC ctorProc = (CTORFUNC)::GetProcAddress(hModule, ctorName); PRINTFUNC printProc = (PRINTFUNC)::GetProcAddress(hModule, printName); if (ctorProc == NULL || printProc == NULL) { printf("NOT FOUND: ctor or print\r\n"); return 1; } // 해당 클래스의 객체 크기만큼 미리 메모리를 할당 int size = sizeof(CWin32Project1); char *pBytes = new char[size]; // 할당된 메모리가 바로 this 포인터 역할을 함. // 생성자를 호출해 인스턴스를 초기화하고, ctorProc(pBytes); // 멤버 함수를 호출 printProc(pBytes); // 출력 결과: 500 delete [] pBytes; return 0; } </pre> <br /> <a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=950&boardid=331301885'>첨부한 파일은 위의 코드를 포함</a>하고 있습니다.<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
4444
(왼쪽의 숫자를 입력해야 합니다.)