Size, ShareName); ShareP=(char *)MapViewOfFile(fh, FILE_MAP_ALL_ACCESS, 0,0,0); if (GetLastError()!=ERROR_ALREADY_EXISTS) ZeroMemory(ShareP,size); // 共享区初始化 return(fh); } char * ShareP=NULL; void test() // 申请一块128个字节的字符数组 { HANDLE fh=GetShare(ShareP,128,"ShareForMyProg"); for (int i=0;i<128;i++) ShareP[i]=i; CloseHandle(fh); }
如果你的多个程序之间或同一个程序多次同时运行,也可借助这个办法进
变量通讯;
在VC++中,若要为DLL定义一个共享内存段更简单,这是一种直接定义的
办法:
#pragma data_seg("Shared") int x,y; char s[128]; #pragma data_seg #pragma comment(linker,"/section:Shared,rws")
真简单,可惜在C++BUILDER5.0中经试验好象不能接受这种方法;
对于BCB,能不能实现DLL中直接定义共享内存块内,请看下列一段文字:
http://community.borland.com/article/0,1410,20008,00.html /// C++Builder 4.0 is the first C++Builder compiler that supports shared memory segments. This document explains how to use this feature in windows DLL. To change the data segment and the class name, you need to add #pragma option -zR[SEGMENT NAME] and #pragma option -zT[CLASS NAME] to the file you want the data shared from. Below is the source file I am going to export the integer named ''data'': File: SharedData.cpp //--------------------------------------------------------------------------- // Borland C++Builder // Copyright (c) 1987, 1999 Inprise Corporation. All Rights Reserved. //--------------------------------------------------------------------------- #pragma option -zRSHSEG // change default data segment name #pragma option -zTSHCLASS // change default data class name // Here is the initialized data that will be shared. int data = 0; Notice that the segment name for this file is: SHSEGSHCLASS. A .def file is required for the linker to create the shared segement. Below is what the .def file looks like: File: Shared.def LIBRARY SHAREDDLL SEGMENTS SHSEG CLASS ''SHCLASS'' SHARED
可见C++BUILDER4.0与DELPHI已能提供直接实现DLL内存段共享问题,请高手邦忙一起
试一试:在BCB或DELPHI具体应怎样做?
四
// 下面的程序将产生有三个导出函数的MouseHook.DLL
#include <windows.h> #pragma argsused typedef // 为共享区定义结构 struct { POINT MouseLoc; // 存放鼠标位置 HHOOK NewHook; // 存放新钩子句柄 int LoadCount; // DLL装入次数计数 } TShareMem; TShareMem *ShareMem=NULL; HINSTANCE DllHinst; int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void* lpReserved) { DllHinst=hinst; static HANDLE fh; // DLL共享区句柄 if (reason==DLL_PROCESS_ATTACH) // DLL入口 { // 为共享区申请共享单元 fh=CreateFileMapping((HANDLE)-1,0, PAGE_READWRITE,0,
|