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(, );
nRet = Sub(, ); QMath m;
nRet = m.Add(, );
nRet = m.Sub(, ); return ;
}

显示加载:

需要文件:*.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 ;
ADD_PROC Add = (ADD_PROC)::GetProcAddress(hModule, "Add");
SUB_PROC Sub = (SUB_PROC)::GetProcAddress(hModule, "Sub");
int nRet = ;
{
if ( Add )
nRet = Add(, );
if ( Sub )
nRet = Sub(, );
}
::FreeLibrary(hModule);
hModule = NULL; return ;
}
上一篇:PAT 甲级 1154 Vertex Coloring


下一篇:从0开始的Python学习015输入与输出