您的位置:首页 > 其它

VC学习笔记9动态链接库

2015-08-03 14:00 274 查看
静态链接库

首先我们来创建一个静态链接库工程

在VC++6.0环境下点Projects中的Win32 Static Library

我在这里随意写了个工程teststatic

新建一个teststatic.h头文件和一个teststatic.cpp源文件

下面是两个文件的的内容:

teststatic.h里的内容:

int TestAdd(int a,int b);

double TestPow(double a,double b);

teststatic.cpp里的内容:

#include"teststatic.h"

#include"math.h"

int TestAdd(int a,int b)

{

return a+b;

}

double TestPow(double a,double b)

{

return pow(a,b);

}

编译,生成一个teststatic.lib文件

现在如果需要实现调用,只需要将.lib和.h文件加入要调用的工程。

下面范例:

#include<iostream>

#include"teststatic.h"

#pragma comment (lib,"teststatic.lib")

using namespace std;

int main()

{

printf("%lf\n",TestPow(2.0,3.0));

}

动态连接库

在VC++6.0环境下点Projects中的Win32 Dynamic-Link Library

我在这里随意写了个工程dlltest

希望创建什么类型的DLL?选第二个,一个简单的DLL工程

新建一个头文件dlltest.h

在上面加上这些代码:

#include "stdafx.h"

#define EXPORT __declspec(dllexport)

extern "C" EXPORT void __stdcall TestPut(char *pText);

然后再创建一个dlltest.def文件

在上面加上代码:(这个是用来生成lib文件的不加也是可以的)

LIBRARY dlltest.dll

EXPORTS

TestPut=TestPut

在dlltest.cpp的DllMain函数下面加上全局函数:

void __stdcall TestPut(char *pText)

{

MessageBox(NULL,pText,"Message",0);

}

编译后在Debug文件中能找到生成的两个文件:

dlltest.dll

dlltest.lib

好了现在开始调用:

在一个新的工程里加入.dll文件

在需要调用的地方调用,我这里是:

typedef void (__stdcall*funShowInfo)(char*); //定义函数指针funShowInfo

void CGgDlg::OnButton1()

{

char ss[4]="sss";

HINSTANCE hMod=LoadLibrary("dlltest.dll"); //定义dll数据结构加载

if(hMod!=NULL)

{

funShowInfo si;

si=(funShowInfo)GetProcAddress(hMod,"TestPut"); //载入函数指针

if(si)

si(ss); //用函数指针调用

}

FreeLibrary(hMod); //释放动态链接库

}

当然,我不加__stdcall也行,那么这个是什么意思呢

__stdcall: WINAPI默认函数调用协议,参数由右向左入栈,函数调用后由被调用函数清除栈内数据

__cdecl: C++默认函数调用协议,参数由右向左入栈,函数调用后由函数调用者清除栈内数据

如果用默认的__cdecl每次调用后需要由调用者清除内存的代码,故不方便,因此最好加上__stdcall
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: