DLL入门

DllTest工程

QMath.h

#pragma once

#ifdef API_EXPORT
#define DLL_CLASS __declspec(dllexport)
#define DLL_API extern "C" __declspec(dllexport)
#else
#define DLL_CLASS __declspec(dllimport)
#define DLL_API extern "C" __declspec(dllimport)
#endif

DLL_API int Add(int a, int b);
DLL_API int Sub(int a, int b);


class DLL_CLASS QMath
{
public:
    int Add(int a, int b);
    int Sub(int a, int b);
};

QMath.cpp

#include "StdAfx.h"

#define API_EXPORT
#include "QMath.h"

int Add(int a, int b)
{
    return (a+b);
}

int Sub(int a, int b)
{
    return (a-b);
}

int QMath::Add(int a, int b)
{
    return (a+b);
}

int QMath::Sub(int a, int b)
{
    return (a-b);
}

dllmain.cpp

#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
                     )
{

    return TRUE;
}

Test测试工程:

隐式加载:

需要三个文件:*.h、*.lib、*.dll

//隐式加载
#include "../DllTest/QMath.h"
#pragma comment(lib, "../Debug/DllTest.lib")
int _tmain(int argc, _TCHAR* argv[])
{
    int nRet = Add(1, 2);
    nRet = Sub(1, 2);

    QMath m;
    nRet = m.Add(1, 2);
    nRet = m.Sub(1, 2);

    return 0;
}

显示加载:

需要文件:*.dll

//显示加载
typedef int (*ADD_PROC)(int a, int b);
typedef int (*SUB_PROC)(int a, int b);
int _tmain(int argc, _TCHAR* argv[])
{
    HMODULE hModule = ::LoadLibrary(_T("../Debug/DllTest.dll"));
    if ( NULL == hModule )
        return 0;
    ADD_PROC Add = (ADD_PROC)::GetProcAddress(hModule, "Add");
    SUB_PROC Sub = (SUB_PROC)::GetProcAddress(hModule, "Sub");
    int nRet = 0;
    {
        if ( Add )
            nRet = Add(1, 2);
        if ( Sub )
            nRet = Sub(1, 2);
    }
    ::FreeLibrary(hModule);
    hModule = NULL;

    return 1;
}
原文地址:https://www.cnblogs.com/qintangtao/p/3259699.html