DLL知识小结

目标:在dll中实现一个函数,用一个exe对函数进行显式的调用,只需将dll放在vc同一工程下。

 

动态链接库的实现

#include "stdafx.h"

BOOL APIENTRY DllMain( HANDLE hModule,
                       DWORD  ul_reason_for_call,
                       LPVOID lpReserved
      )
{
    return TRUE;
}

//很简单,实现两个整数的相加

extern "C" __declspec(dllexport) int test (int x, int y) //extern "C" __declspec(dllexport) 使用c方式调用函数,同时声明了输出函数。

//不需要什么头分件和def,如果需要查看编译的dll中是否导出该函数,可以使 用dumpbin -exports **.dll


{
 int nResult = x+ y;
 return nResult;
}

 

exe的实现

#include "stdafx.h"
 

int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{

 HINSTANCE hdll = LoadLibrary("dlldemo1.dll");
 typedef   int   (* LPFNDLLFUNC)(int ,int);  //定义与导出函数类型一致的函数。
 LPFNDLLFUNC   lpfnDllFunc;
 lpfnDllFunc = (LPFNDLLFUNC)GetProcAddress(hdll,"test");
   if (!lpfnDllFunc)
   {
      // handle the error
      FreeLibrary(hdll);
      return 0;
   }
   else
   {
      // call the function
      int x = lpfnDllFunc(7, 9);
   }

 return 0;
}

extern "C"有啥用?

当你的dll是用C++写的 而exe是C写的时候 在dll中导出函数需要加上extern "C",不然vc的编译器可能改变函数名字,而使exe不能识别。。。。。

你可能感兴趣的:(学海拾贝)