VC++ 动态DLL模板-_stdcall约定

1、VS2003新建DLL项目dllTest

2、项目dllTest中添加脚本lib.h,代码如下:

 

1 #ifndef LIB_H
2 #define LIB_H
3 int _stdcall add(int x,int y);
4 int _cdecl mius(int x,int y);
5 #endif 

 

3、项目dllTest中添加脚本lib.cpp,代码如下:

 

 1 #include "lib.h"
 2 #include "windows.h"
 3 #include "stdio.h"
 4 
 5 BOOL APIENTRY DllMain( HANDLE hModule, 
 6                       DWORD  ul_reason_for_call, 
 7                       LPVOID lpReserved
 8                       )
 9 {
10     switch (ul_reason_for_call)
11     {
12     case DLL_PROCESS_ATTACH:
13         printf("\nprocess attach of dll");
14         break;
15     case DLL_THREAD_ATTACH:
16         printf("\nthread attach of dll");
17         break;
18     case DLL_THREAD_DETACH:
19         printf("\nthread detach of dll");
20         break;
21     case DLL_PROCESS_DETACH:
22         printf("\nprocess detach of dll");
23         break;
24     }
25     return TRUE;
26 }
27 //用任何一种方法输出函数时,确保用_stdcall调用约定, _stdcall 调用约定是用来调用Win32 API函数。
28 //_stdcall 以相反的顺序(从右到左) 把参数推入栈中
29 int _stdcall add(int x,int y)
30 {
31     return x + y;
32 }
33 
34 int _cdecl mius(int x,int y)
35 {
36     return x - y;
37 }

 

4、项目dllTest中添加脚本lib.def,代码如下:

1 LIBRARY LIB
2 EXPORTS
3 add @ 1
4 mius @ 2

5、build生成dllTest.dll文件

 

6、添加检测项目dllCall

7、添加主程序脚本dllCall.cpp,代码如下:

特别说明:如果通过VC++编写的DLL欲被其他语言编写的程序调用,应将函数的调用方式声明为__stdcall方式,WINAPI都采用这种方式,而C/C++缺省的调用方式却为__cdecl。

 1 #include "stdafx.h"
 2 #include "windows.h"
 3 
 4 typedef int (_stdcall * lpAddFun)(int,int);
 5 typedef int (_cdecl * lpMiusFun)(int,int);
 6  
 7 int main(int argc, char* argv[])
 8 {
 9     HINSTANCE hDll; 
10     lpAddFun addFun;
11     lpMiusFun miusFun;
12     hDll = LoadLibrary("..\\Debug\\dllTest.dll");
13     if (hDll != NULL)
14     {
15         addFun = (lpAddFun)GetProcAddress(hDll,"add");    
16         //或addFun = (lpAddFun)GetProcAddress(hDll,MAKEINTRESOURCE(1));
17         //MAKEINTRESOURCE直接使用导出文件中的序号
18         if(addFun!=NULL)
19         {
20             int result =  addFun(2,3);    
21             printf("\ncall add in dll:%d",result);
22         }    
23 
24         miusFun = (lpMiusFun)GetProcAddress(hDll,"mius");    
25         //或addFun = (lpAddFun)GetProcAddress(hDll,MAKEINTRESOURCE(1));
26         //MAKEINTRESOURCE直接使用导出文件中的序号
27         if(miusFun!=NULL)
28         {
29             int result =  miusFun(2,3);    
30             printf("\ncall mius in dll:%d",result);
31         }
32         FreeLibrary(hDll);
33     }
34     getchar();
35       return 0;
36 }

8、Ctrl+F5调试运行结果如下:

 

 

转载于:https://www.cnblogs.com/jonathan236/p/3387973.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值