用vc写DLL - -

来源:互联网 发布:android c语言编译器 编辑:程序博客网 时间:2024/05/01 03:20
  

通过MFC AppWizard(dll)输入DLL程序的名称"DLL"后点击"Finish"按钮生成一个DLL程序的基本结构,其中在运行到图二界面时,我们可以选择第一项按钮"Regular DLL with MFC statically linked" 生成常规静态DLL,也可以选择第二项按钮"Regular DLL using shared MFC DLL"生成常规动态DLL,后者的体积远远小于前者。现在的任务是在运行DLL时弹出一个显示"This is My DLL"字样的对话框,点击"确定"后返回调用程序。为此,需要在DLL工程中插入一个对话框资源(该对话框类名为CMyDlg),在DLL.cpp程序开头输入以下代码:

#include "MyDlg.h"
在DLL.cpp程序最后一行代码"CDLLApp theApp;"后面输入以下代码:

extern "C" _declspec(dllexport) int MyTest()
{
  AFX_MANAGE_STATE(AfxGetStaticModuleState());

//
  CMyDlg dlg;
  dlg.DoModal();
  return 0;
}


  对DLL编译后生成DLL.dll程序。

  然后,进入主程序TestDll,利用ClassWizard对命令按钮代码段添加下列代码:

void CTestDLLDlg::OnButton1()
{
 // TODO: Add your control notification handler code here
  typedef int(_cdecl *MM)();
  HINSTANCE hinstDLL=NULL;
  hinstDLL=LoadLibrary("DLL.dll");
  if (hinstDLL)
  {
   MM Proc;
   Proc = (MM)GetProcAddress(hinstDLL,"MyTest");
   int iTemp = Proc();
      //int iTemp = GetProcAddress(hinstDLL,"MyTest");
   FreeLibrary(hinstDLL);
  }
  else
  {
   AfxMessageBox("Not found dll!");
  }
}


  为了让TestDll能够调用DLL.dll程序,需要让前者能够"看见" DLL程序。一个Windows程序定位DLL的次序是, 1.包含EXE文件的目录,2.进程的当前工作目录, 3.Windows系统目录, 4.Windows目录,5.列在Path环境变量中的一系列目录。为此,需要将DLL.dll放到上述相关目录中,这样执行主程序TestDll,点击命令按钮就显示以下DLL运行结果.

下面是我想要共享dll中的数据,在dll文件中这样:
#pragma data_seg(".MYDATA")

static int count=0;//是不是静态的没什么关系

#pragma data_seg()

#pragma comment(linker,"/SECTION:.MYDATA,RWS")//很重要,没有就不好使了。


上面是MFC的东西,比较简单。当然了win32也不难。
//win32dll.h
#ifdef __cplusplus
#define EXPORT extern "C" __declspec(dllexport)
#else
#define EXPORT __declspec(dllexport) 
#endif

EXPORT void setCount(int count);
EXPORT int getCount();//一定要有export表示输出

//win32dll.cpp
#include "windows.h"
#include "win32dll.h"

int WINAPI DllMain (HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved)
{
    return TRUE;
}

void setCount(int count){

}
int getCount(){
return 10;
}
今天在来添一笔:
::FreeLibrary(hinstDLL)//这句话一定要注意,如果那个实例卡查了。内存错误了,一定是他搞的鬼。他是来释放dll句柄的。

原创粉丝点击