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

来源:互联网 发布:无线淘宝收藏链接 编辑:程序博客网 时间:2024/06/05 18:46


先创建一个动态库dll工程

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

dlltest.h

//dlltest.hextern __declspec(dllexport) int FuncTest();

dlltest.cpp

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

dlltest.def

LIBRARY"testmydll"EXPORTSFuncTest

 

 

编译后生成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