有关内存映射的问题???高手帮一下忙吧··· ( 积分: 100 )

  • 主题发起人 主题发起人 jyg
  • 开始时间 开始时间
J

jyg

Unregistered / Unconfirmed
GUEST, unregistred user!
/// PShare := PShareMem(MapViewOfFile(HMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
是什么意思???
MapViewOfFile 的返回值是一个内存地址指针。
PShare := PShareMem(指针)是什么意思!!
// if WaitForSingleObject(HMapMutex, REQUEST_TIMEOUT)
= WAIT_FAILED then
这个是什么意思????


unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;

const
WM_DATA = WM_USER + 1024;
type
PShareMem = ^TShareMem;
TShareMem = record
Data: array[0..255] of char;
end;
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }

end;

var
Form1: TForm1;
PShare: PShareMem;
implementation

{$R *.DFM}
var
HMapping: THandle;
HMapMutex: THandle;
const
MAPFILESIZE = 1000;
REQUEST_TIMEOUT = 1000;

procedure OpenMap;
begin
{创建一个文件映射内核对象}
HMapping := CreateFileMapping(
$FFFFFFFF,
nil,
PAGE_READWRITE,
0,
SizeOf(TShareMem),
{这个文件映射对象的名字用于与其他进程共享该对象,}
pchar('Map Name')
);
if (hMapping = 0) then
begin
ShowMessage('不能创建内存映射文件');
Application.Terminate;
exit;
end;
{将文件数据映射到进程的地址空间}
{当创建了一个文件映射对象之后,仍然必须让系统为文件的数据保留
一个地址空间区域,并将文件的数据作为映射到该区域的物理存储器进行提交。
}
PShare := PShareMem(MapViewOfFile(HMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0));
if PShare = nil then
begin
CloseHandle(HMapping);
ShowMessage('Can''t View Memory Map');
Application.Terminate;
exit;
end;

{既然我们通过pvFile得到了映象视图的起始地址,那么可以对视图做一些操作了}
end;

procedure CloseMap;
begin
if PShare <> nil then
{从进程的地址空间中撤销文件数据的映象}
UnMapViewOfFile(PShare);
if HMapping <> 0 then
CloseHandle(HMapping);
end;

function LockMap: Boolean;
begin
Result := true;
{创建互斥对象}
HMapMutex := CreateMutex(nil, false,
pchar('MY MUTEX NAME GOES HERE'));
if HMapMutex = 0 then
begin
ShowMessage('不能创建互斥对象');
Result := false;
end else begin
if WaitForSingleObject(HMapMutex, REQUEST_TIMEOUT)
= WAIT_FAILED then
begin
ShowMessage('不能对互斥对象加锁!');
Result := false;
end
end
end;

procedure UnlockMap;
begin
{关闭文件映射对象和文件对象}
ReleaseMutex(HMapMutex);
CloseHandle(HMapMutex);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
str: pchar;
begin
str := pchar('简单的共享内存的例子');
CopyMemory(@(pShare^.data), Str, Length(str));
{发送消息表明有数据}
PostMessage(FindWindow(nil, 'MyForm'), WM_DATA, 1, 1)
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
UnlockMap;
CloseMap;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
OpenMap;
LockMap;
end;

end.
////
 
PShare := PShareMem(指针) 就是将返回的共享内存头指针强制转换为PShareMem后再赋给PShare
 
if WaitForSingleObject(HMapMutex, REQUEST_TIMEOUT)
= WAIT_FAILED then
等待互斥对象发信号(可用),REQUEST_TIMEOUT是超时时间常量
 
谢谢,我一开始没有想好,以为是指针数组了,哈哈!!
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
I
回复
0
查看
576
import
I
I
回复
0
查看
814
import
I
后退
顶部