VS创建dll和调用dll

自己创建自己的dll库,有时候会显得特别方便,而且非常简单。。。下面就简单在VS2005上介绍dll库创建和调用的全过程。 
一:创建自己的dll 
1)创建一个win32 console application 选择dll 
然后创建一个DllTest.cpp code如下: 

// lib3.cpp : 定义 DLL 应用程序的入口点。 
// 

#include "stdafx.h" 
extern   "C" _declspec(dllexport) int Add(int,int); //注意了 

#ifdef _MANAGED 
#pragma managed(push, off) 
#endif 

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

int _declspec(dllexport) Add(int a, int b) 
{ 
    //return MessageBox(NULL, L"GOOD", L"Caption", 0 );] 
    return a+b; 
} 


#ifdef _MANAGED 
#pragma managed(pop) 
#endif 

编译便可生成dll文件。

二: 调用测试刚才生成的dll。 
上面的dll有一个加法Add的函数,记得刚上面的那个dll拷贝到下面这个main函数所在的文件同目录下,main代码如下: 

//#include "stdafx.h" 
#include <windows.h> 
#include <iostream> 
typedef int (* MYPROC)(int,int); //注意别写错了; 
int main(int argc, char* argv[]) 
{ 
  int error; 
  MYPROC pFunc; 
  HMODULE hdll_lib =::LoadLibraryEx(TEXT("DllTest.dll"),NULL,0); 
  // 
  if(hdll_lib == NULL) 
  { 
    error = GetLastError(); 
    printf("error = %d",error); 
    FreeLibrary(hdll_lib); return -1; 
  } 
  pFunc=(MYPROC)GetProcAddress(hdll_lib, "Add"); // 
  if(!pFunc) 
  { 
    error = GetLastError(); 
    printf("error = %d",error); 
    FreeLibrary(hdll_lib); return -1; 
  } 
  int a=pFunc(1,2);// 
  printf("%d\n",a); 
  FreeLibrary(hdll_lib); 
  system("pause"); 
  return 0; 
}
原文地址:https://www.cnblogs.com/xiongjiaji/p/2476570.html