您的位置:首页 > 编程语言 > C语言/C++

VS2010 c++生成和调用dll例子

2016-08-25 19:40 471 查看
参考 http://blog.csdn.net/big_wang5/article/details/8216557

c++新手

一、DLL简介

包含能被可执行程序或其他DLL调用的函数。动态链接提供了一种方法,使进程可以调用不属于其可执行代码的函数。函数的可执行代码位于一个 DLL 中,该 DLL 包含一个或多个已被编译、链接并与使用它们的进程分开存储的函数。

若要访问dll中的函数,该函数必须是导出的(_declspec(dllexport)关键字),在命令提示符下使用dumpbin函数查看导出情况。

二、DLL的2中加载方式:隐式连接和显示加载。

1.隐式连接

生成dll

使用_declspec(dllexport)关键字导出函数,使用静态调用dll

VS2010中新建控制台程序,在“应用程序设置”页面的“应用程序类型”下,选择“DLL”和空项目。

创建头文件,命名为DllDemo.h

/**********************************************/
/*FileName:DllDemo.h                          */
/**********************************************/

#ifdef DllDemoAPI
#else
#define DllDemoAPI _declspec(dllimport)
#endif

DllDemoAPI int add(int a, int b);
DllDemoAPI int subtract(int a, int b);
DllDemoAPI int multiple(int a, int b);

class DllDemoAPI Point
{
public:
void Print(int x, int y);
};


创建源文件,命名为DllDemo.cpp

/**********************************************/
/*FileName:DllDemo.cpp                        */
/**********************************************/

#define DllDemoAPI _declspec(dllexport)
#include "DllDemo.h"
#include <stdio.h>

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

DllDemoAPI int subtract(int a, int b)
{
return a-b;
}

DllDemoAPI int multiple(int a, int b)
{
return a*b;
}

DllDemoAPI void Point::Print(int x, int y)
{
printf("x=%d,y=%d",x,y);
}


生成,Debug目录里生成了以下这些文件



调用dll

新建控制台应用程序InvokeDll,默认即可。

InvokeDll.cpp中添加如下代码:

// InvokeDll.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include "F:\PCLBOOK\DllDemo\DllDemo\DllDemo.h"

int _tmain(int argc, _TCHAR* argv[])
{
/*加载dll函数调用方式为默认调用方式*/

printf("5+3=%d\n",add(5,3));

Point p;
p.Print(5,3);

system("pause");
return 0;
}


右键InvokeDll项目,选择“属性”选项,在“链接器”选择的字选项“输入”|“外部依赖项”中添加DemoDll.lib

编译运行得结果



错误提示:

1、


项目–属性–清单工具–输入输出–嵌入式菜单–将是改成否即可。

2、error LNK1104: 无法打开文件“DllDemo.lib”

在“属性”-》链接器-》常规-》附加库目录 和“属性”-》链接器-》输入-》附加依赖项 中都添加上了Dll1.lib库文件的完整路径如“F:\PCLBOOK\DllDemo\Debug\DllDemo.lib”后就成功了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: