Dll入门范例

范例程序下载:http://download.csdn.net/detail/wangyao1052/4918041

Dll1.h

View Code
#ifndef _DLL1_H_
#define _DLL1_H_

#ifndef DLL1_API
#define DLL1_API __declspec(dllimport)
#endif

// 导出函数
DLL1_API int add(int a, int b);

// 导出类
class DLL1_API A
{
public:
    int add(int a, int b);
};

// 导出部分类成员函数 
class B
{
public:
    DLL1_API int add(int a, int b);
    void Hello();
};

#endif

Dll1.cpp

View Code
#define DLL1_API __declspec(dllexport)
#include "Dll1.h"

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

int A::add(int a, int b)
{
    return a+b;
}

int B::add(int a, int b)
{
    return a+b;
}

void B::Hello()
{
    return;
}

使用范例

View Code
#include "..\\Dll1\\Dll1.h"

void CTestDlg::OnBnClickedButton1()
{
    // TODO: Add your control notification handler code here

    // 测试导出函数
    CString cstr;
    cstr.Format(TEXT("1+3=%d"), add(1, 3));
    AfxMessageBox(cstr);

    // 测试导出类
    A a;
    cstr.Format(TEXT("1+4=%d"), a.add(1, 4));
    AfxMessageBox(cstr);

    // 测试到处部分类成员函数
    B b;
    cstr.Format(TEXT("4+5=%d"), b.add(4, 5));
    AfxMessageBox(cstr);
}

说明一

***************************************************************
1.在Dll中抛出异常,在调用Dll的程式中是可以catch的.
2.C++编写的动态链接库给C调用,为了不发生名字改编,需加上extern "C"
如:#define DLL_API extern "C" __declspec(dllexport)
但注意,加了extern "C"之后,不发生名字改编的前提是函数采用的是默认的C调用约定,
即__cdecl.若采用__stdcall调用约定,仍然会发生名字改编.
eg. int __stdcall add(int a, int b);
3.int add(int a, int b);
等价于 int __cdecl add(int a, int b);
4.利用dumpbin查看.exe或DLL的导入导出状况
dumpbin -imports xxx.exe或xxx.dll
dumobin -exports xxx.exe或xxx.dll
dumpbin.exe所在的目录: Visual Studio安装目录的VC\bin目录下.
当然更好的方式是使用可视化的工具Depends.exe查看
***************************************************************

说明二

***************************************************************
利用模块文件xxx.def定义DLL导出函数的名字
1.建立xxx.def文件加入工程
2.xxx.def
LIBRARY xxx
EXPORTS
Add=add @ 1
3.cpp File
int add(int a, int b)
{
    return a+b;
}
***************************************************************

如何动态加载Dll

View Code
// 1.LoadLibrary
HINSTANCE hinstLib = LoadLibrary(TEXT("xxx.dll"));
if (hinstLib == NULL)    // LoadLibrary failed
{
    // To get extended error information, call GetLastError().
    ......
}

// 2.GetProcAddress
typedef int (*MyProc)(int a, int b);
MyProc ProcFunTest = (MyProc)GetProcAddress(hinstLib, "xxx");
if (ProcFunTest == NULL)    // GetProcAddress failed
{
    // To get extended error information, call GetLastError().
    ......
}

// 3.Call function
ProcFunTest(1, 2);

// 4.FreeLibrary
FreeLibrary(hinstLib);
原文地址:https://www.cnblogs.com/Hisin/p/2829546.html