Dll入门范例

来源:互联网 发布:鼎捷软件怎么样 编辑:程序博客网 时间:2024/05/29 12:29


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.LoadLibraryHINSTANCE hinstLib = LoadLibrary(TEXT("xxx.dll"));if (hinstLib == NULL)    // LoadLibrary failed{    // To get extended error information, call GetLastError().    ......}// 2.GetProcAddresstypedef 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 functionProcFunTest(1, 2);// 4.FreeLibraryFreeLibrary(hinstLib);
复制代码

 

原创粉丝点击