1、VS2003新建DLL项目dllTest
2、项目dllTest中添加脚本lib.h,代码如下:
1 //lib.h 2 #ifndef LIB_H 3 #define LIB_H 4 extern "C" int __declspec(dllexport) add(int x,int y); 5 extern "C" int __declspec(dllexport) mius(int x,int y); 6 #endif
3、项目dllTest中添加脚本lib.cpp,代码如下:
1 #include "lib.h" 2 int add(int x,int y) 3 { 4 return x + y; 5 } 6 int mius(int x,int y) 7 { 8 return x - y; 9 }
4、build生成dllTest.dll文件
5、添加检测项目dllCall
6、添加主程序脚本dllCall.cpp,代码如下:
特别说明:LoadLibrary、GetProcAddress及FreeLibrary是系统API,故需要引用windows.h
1 #include "stdafx.h" 2 #include "windows.h" 3 4 typedef int ( * lpAddFun)(int,int); 5 6 int main(int argc, char* argv[]) 7 { 8 HINSTANCE hDll; //DLL句柄 9 lpAddFun addFun; //函数指针 10 hDll = LoadLibrary("..\Debug\dllTest.dll"); 11 if (hDll != NULL) 12 { 13 addFun = (lpAddFun)GetProcAddress(hDll,"add"); 14 if(addFun!=NULL) 15 { 16 int result = addFun(2,3); 17 printf("2 + 3 = %d ",result); 18 } 19 addFun = (lpAddFun)GetProcAddress(hDll,"mius"); 20 { 21 int result = addFun(2,3); 22 printf("2 - 3 = %d ",result); 23 } 24 FreeLibrary(hDll); 25 } 26 return 0; 27 }
7、Ctrl+F5调试运行结果如下: