Windows with Delphi Windows API (94) Windows Filesystem (229) Windows Forms (527) Windows Graphics (1092)
Exchange Links About this site Links to us
|
Shared memory (Delphi 32bit)
This article has not been rated yet. After reading, feel free to leave comments and rate it.
This shows how to use shared memory in a DLL with Delphi 32bit. Use the functions OpenMap and CloseMap.
Any two or more applications or DLLs may obtain pointers to the same physical block of memory this way.
PMapData will point to a 1000 byte buffer in this example, this buffer being initialized to #0's the first time in.
One potential problem is synchronizing access to the memory. You may accomplish this through the use of mutexes:
- Call the function LockMap before writing (and reading?) to the memory mapped file.
- Be sure to call UnlockMap immediately when done updating.
From: John Crane:
 | |  | | var
HMapping: THandle;
PMapData: Pointer;
const
MAPFILESIZE = 1000;
procedure OpenMap;
var
llInit: Boolean;
lInt: Integer;
begin
HMapping := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE,
0, MAPFILESIZE, pchar('MY MAP NAME GOES HERE'));
llInit := (GetLastError() <> ERROR_ALREADY_EXISTS);
if (hMapping = 0) then
begin
ShowMessage('Can''t Create Memory Map');
Application.Terminate;
exit;
end;
PMapData := MapViewOfFile(HMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if PMapData = nil then
begin
CloseHandle(HMapping);
ShowMessage('Can''t View Memory Map');
Application.Terminate;
exit;
end;
if (llInit) then
begin
memset(PMapData, #0, MAPFILESIZE);
end
end;
procedure CloseMap;
begin
if PMapData <> nil then
UnMapViewOfFile(PMapData);
if HMapping <> 0 then
CloseHandle(HMapping);
end;
var
HMapMutex: THandle;
const
REQUEST_TIMEOUT = 1000;
function LockMap:Boolean;
begin
Result := true;
HMapMutex := CreateMutex(nil, false,
pchar('MY MUTEX NAME GOES HERE'));
if HMixMutex = 0 then
begin
ShowMessage('Can''t create map mutex');
Result := false;
end
else
begin
if WaitForSingleObject(HMapMutex,REQUEST_TIMEOUT)
= WAIT_FAILED then
begin
ShowMessage('Can''t lock memory mapped file');
Result := false;
end
end
end;
procedure UnlockMap;
begin
ReleaseMutex(HMixMutex);
CloseHandle(HMixMutex);
end; | |  | |  |
Comments:
|
anonymous from India
|
|
|
good article but leaves a lot of stuff to imagination. a working example would have been perfect
|
|
anonymous from Latvia
|
|
|
Line: 'memset(PMapData, #0, MAPFILESIZE);' is wrong. It's not C.
In Delphi one should use FillChar(PMapData^, MAPFILESIZE, 0);
|
|
anonymous from United Kingdom
|
|
|
Should also replace all instances of 'HMixMutex' with 'HMapMutex'.
He obviously didn't copy and paste this from a working app!! lol
Great example though - nice and simple and very powerful.
|
|