您的位置:首页 > 其它

眼过千遍不如手过一遍——简单动态链接库的编写

2010-10-26 16:30 399 查看
链接库文件TestDLL.h

#pragma once

extern "c" int _declspec(dllexport)add(int ,int);//注意这里不能是_stdcall,否则编译出错,具体原因我也不知呀!


链接库文件TestDLL.cpp

#include "TestDLL.h"

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


测试链接文件testlink.cpp

#include<iostream>
#include<windows.h>

typedef (*inport)(int ,int );

int main()
{
HINSTANCE hdll; //dll句柄
inport addnew; //新函数指针

hdll=LoadLibrary(".../TestDLL.dll");

if(hdll==NULL)
{
std::cout<<"load dll error!"<<std::endl;
}

addnew=(inport)GetProcAddress(hdll,"add");

std::cout<<addnew(100,60)<<std::endl;

return 0;
}


输出结果:

160

在TestDLL中再创建DLLMAIN函数如下:

#include <iostream>
#include <windows.h>

using namespace std;

bool APIENTRY DllMain(HANDLE hMoudole,DWORD ul_reason_for_call,LPVOID lpReserved)
{
switch(ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
cout<<"process attach of dll"<<endl;
break;
case DLL_THREAD_ATTACH:
cout<<"thread attach of dll"<<endl;
break;
case DLL_THREAD_DETACH:
cout<<"thread detach of dll"<<endl;
break;
case DLL_PROCESS_DETACH:
cout<<"process detach of dll"<<endl;
}
return true;
}


则输出结果为:

process attach of dll
160
process detach of dll

以上是动态调用(程序在需要的时候再加载所需要的DLL,此种用法比较灵活)

再来看下静态调用,与动态调用不同的是,此种调用在程序编译时就将DLL的加载信息LIB编译进EXE中,当应用程序需要时便从相应的LIB文件中取得DLL的信息来加载DLL,通过符号名来实现对DLL函数的动态链接,与调用内部函数没有区别!

将调用函数testlink.cpp改写成这样:

#include <iostream>
#include <windows.h>

#include "F:/学习资料/C++编程/TestDLL/TestDLL.h"
#pragma comment(lib,"F://学习资料//C++编程//TestDLL//Debug//TestDLL.lib")

extern "C" int _declspec(dllimport)add(int a,int b);

int main()
{
std::cout<<add(100,60)<<std::endl;

return 0;
}


预期输出结果为

process attach of dll
160
process detach of dll

但编译时出现1个警告:inconsistent dll linkage. dllexport assumed. 未出现错误

而执行时提示:无法启动应用程序,因为计算机中丢失TestDLL.dll

具体原因未知,待以后解开.....
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: