IPC란 무엇인가 (MSDN) - http://msdn.microsoft.com/en-us/library/aa365574(v=VS.85).aspx


IPC 기법 중 하나인 FileMapping.
프로세스간 데이터 공유를 위해서도 사용하며,
대용량 파일을 좀 더 빠르게 주물떡거리기 위해 사용하기도 함.

파일맵핑이란 무엇인가 - http://msdn.microsoft.com/en-us/library/aa366556(v=VS.85).aspx


아래는 간단한 델파이 예제.
예제는 그냥 단순 문자열이지만 조금 손보면 구조체 와리가리도 가능함.


1. FileMapping 클래스.

unit uNamedShareMemory;

interface

uses

  Windows, SysUtils;

type
  TNamedShareMemory=class
    const
      BUF_SIZE=256;
      TMP_NAME='TempName';
    public
      class function Read(Name: String): String;
      class function Write(Name, Msg: String): Boolean;
  end;

implementation

{ TNamedShareMemory }

// 읽기
// _____________________________________________________________________________

class function TNamedShareMemory.Read(Name: String): String;
var
  hMapFile: THandle;
  pBuf: PChar;
begin
  Result:='';
  if Length(Trim(Name))=0 then Name:=Self.TMP_NAME;

  hMapFile:=OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PWideChar(Name));
  if hMapFile=0 then begin
    OutputDebugString(PWideChar(Format('[ERROR] OpenFileMapping = %d', [GetLastError])));
    Exit;
  end;

  pBuf:=MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
  if pBuf=nil then begin
    OutputDebugString(PWideChar(Format('[ERROR] MapViewOfFile = %d', [GetLastError])));
    CloseHandle(hMapFile);
    Exit;
  end;

  Result:=pBuf;
  UnmapViewOfFile(pBuf);
  CloseHandle(hMapFile);
end;

// 쓰기
// _____________________________________________________________________________

class function TNamedShareMemory.Write(Name, Msg: String): Boolean;
var
  hMapFile: THandle;
  pBuf: PChar;
begin
  Result:=False;

  if Length(Trim(Name))=0 then Name:=Self.TMP_NAME;

  hMapFile:=OpenFileMapping(FILE_MAP_ALL_ACCESS, False, PWideChar(Name));
  if hMapFile=0 then begin
    hMapFile:=CreateFileMapping(INVALID_HANDLE_VALUE, nil, PAGE_READWRITE, 0, BUF_SIZE, PWideChar(Name));
    if hMapFile=0 then begin
      OutputDebugString(PWideChar(Format('[ERROR] CreateFileMapping = %d', [GetLastError])));
      Exit;
    end;
  end;

  pBuf:=MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, BUF_SIZE);
  if pBuf=nil then begin
    OutputDebugString(PWideChar(Format('[ERROR] MapViewOfFile = %d', [GetLastError])));
    Exit;
  end;

  CopyMemory(pBuf, PChar(Msg), Length(Msg)*SizeOf(Char));
  UnmapViewOfFile(pBuf);
  Result:=True;
end;

end.





쓰기 프로세스

uses
  uNamedShareMemory;

...
...

procedure TForm1.Button1Click(Sender: TObject);
begin
  TNamedShareMemory.Write('MyName', 'FileMapping!');
end;




읽기 프로세스

uses
  uNamedShareMemory;

...
...

procedure TForm1.Button1Click(Sender: TObject);
begin
  Memo1.Lines.Add(TNamedShareMemory.Read('MyName');
end;


 

Posted by bloodguy
,