一个简单的调用动态库的实例


先创建一个动态库dll工程

工程中添加 dlltest.cpp  dlltest.def  dlltest.h

dlltest.h

//dlltest.h
extern __declspec(dllexport) int FuncTest();

dlltest.cpp

//dlltest.cpp
__declspec(dllexport) int FuncTest(int a )
{
	if (a = 1)
	{
		return 100;
	}
}

dlltest.def

LIBRARY	"testmydll"
EXPORTS
	FuncTest

 

 

编译后生成dlltest.dll  dlltest.lib

再新建一个Win32控制台工程用来调用dlltest.dll  

将dlltest.dll拷贝到Win32的Debug目录下面

Win32项目中dll.cpp文件如下

#include <iostream>   
#include "string"   
#include <stdio.h>  
#include <windows.h>
using namespace std;

int main()
{
	typedef int (*HFUNC)(int a );
	HINSTANCE hDLL = LoadLibrary("testmydll.dll");
	if (hDLL)
	{
		HFUNC hFun = (HFUNC)GetProcAddress(hDLL,"FuncTest");
		if (hFun)
		{
			int a =1;
			int b = hFun(a);
			printf("%d\n",b);
		}
	}

}


 

编译执行则调用了dlltest.dll 打印出100

 

 

 

如果是调用 dlltest.lib的话,就要将dlltest.lib拷贝到工程目录下(Debug上一级),编译的时候就直接链接了,另外还要把头文件 dlltest.h加到工程中

Win32项目中dll.cpp中的代码如下

#include <iostream>   
#include "string"   
#include <stdio.h>  
#include <windows.h>
#include "dlltest.h"
using namespace std;
#pragma comment(lib,"testmydll.lib")
__declspec(dllimport) int FuncTest(int a );
int main()
{
	int b = FuncTest(1);
	printf("%d\n",b);
	return 0;
}


编译执行打印出100

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值