[转]一个简单的调用动态库的实例
转自http://blog.csdn.net/lxh1230119/article/details/8071730
先创建一个动态库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
作者:红山玉龙
出处:http://www.cnblogs.com/yhLinux/
各位看官如果觉得文章对您有用的话,请猛击右下方大姆指给个推荐,让更多的朋友能够看到,以节约搜索解决方案的时间,用来做更有意义的事情o(∩_∩)o
分享知识是快乐的,也应是自由的。欢迎各位朋友转载,请您在转载时帖上本文原文链接,谢谢!
浙公网安备 33010602011771号