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

2014-11-24 09:52:11 · 作者: · 浏览: 0

先创建一个动态库dll工程
工程中添加 dlltest.cpp dlltest.def dlltest.h
dlltest.h
[cpp]
//dlltest.h
extern __declspec(dllexport) int FuncTest();
dlltest.cpp
[cpp]
//dlltest.cpp
__declspec(dllexport) int FuncTest(int a )
{
if (a = 1)
{
return 100;
}
}
dlltest.def
[cpp]
LIBRARY "testmydll"
EXPORTS
FuncTest


编译后生成dlltest.dll
再新建一个Win32控制台工程用来调用dlltest.dll
将dlltest.dll拷贝到Win32的Debug目录下面

Win32项目中dll.cpp文件如下
[cpp]
#include
#include "string"
#include
#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; www.2cto.com
int b = hFun(a);
printf("%d\n",b);
}
}

}


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