Microsoft MVP성태의 닷넷 이야기
VC++: 92. C++ 생성자를 DLL로부터 동적 로드해 객체를 생성한다면? [링크 복사], [링크+제목 복사],
조회: 16900
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

C++ 생성자를 DLL로부터 동적 로드해 객체를 생성한다면?

다음과 같은 질문이 있군요. ^^

C++ DLL로 class를 export후 LoadLibrary로 DLL을 불러와 new로 class 객체를 생성할 수 있는 방법 없을까요
; http://lab.gamecodi.com/board/zboard.php?id=GAMECODILAB_QnA_etc&no=3843&z=

질문의 요지는 이렇습니다. C++ 클래스를 DLL에 구현해 두었는데, 이 클래스의 인스턴스를 외부 EXE/DLL에서 접근해 생성하고 싶다는 것입니다. 검색해 보면 이를 위한 방법을 다음의 글에서 찾을 수 있습니다.

Using classes exported from a DLL using LoadLibrary
; http://www.codeproject.com/Articles/9405/Using-classes-exported-from-a-DLL-using-LoadLibrar

직접 실습을 해볼까요? ^^




우선, Visual Studio에서 C++ Win32 DLL 프로젝트를 "Export symbols" 옵션을 켜서 생성한 후, 기본 포함된 CWin32Project1 클래스의 코드에 다음과 같이 테스트를 위해 필드 n과 Print 함수를 포함시켜 둡니다.

#define WIN32PROJECT1_API __declspec(dllexport)

#include <stdio.h>

class WIN32PROJECT1_API CWin32Project1 {
public:
    int n;
    CWin32Project1(void);

    void Print()
    {
        printf("%d\r\n", n);
    }
};

CWin32Project1::CWin32Project1()
{
    n = 500;
    return;
}

컴파일하고 Visual Studio 명령 프롬프트를 실행시켜 dumpbin.exe를 실행하면 생성자가 export된 심볼을 구할 수 있습니다.

C:\temp\Win32Project1\x64\Debug>dumpbin /exports 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 ??0CWin32Project1@@QEAA@XZ = @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 ?Print@CWin32Project1@@QEAAXXZ = @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

이 값을 이용해 LoadLibrary/GetProcAddress로 함수 포인터를 구하는 코드는 이렇습니다.

#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;
    }


    // Why can't I GetProcAddress a function I dllexport'ed?
    // 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;
}

첨부한 파일은 위의 코드를 포함하고 있습니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 4/1/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2020-06-08 03시31분
[4567] 그냥 DLL 내부에서 new 로 자기자신 생성해서 리턴하고 메인에서 그 함수 포인터 가져와서 호출하면안되나요?
[guest]
2020-06-08 03시48분
@4567 음... 글의 초반에 링크한 원본 질문을 읽어보셨다면 그런 질문을 하지 않으셨을 텐데요.
정성태

... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12431정성태11/27/20209171.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제파일 다운로드1
12430정성태11/27/20209912오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/20209994디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/20208925VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/202010068.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/20208656오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/20209706VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202010135VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202011081.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20208869.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208600.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207797오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/20209000VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202011090오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208471오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/20209752오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/20209781.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202010853VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202010560.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202012826.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/20209789오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209737디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011150.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022448도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011415.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202012984.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...