{
Copyright ?1999 by Delphi 5 Developer's Guide - Xavier Pacheco and Steve Teixeira
} unit MainFrm; interface uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls; const
FName = 'test.txt'; type TMainForm = class(TForm)
btnUpperCase: TButton;
memTextContents: TMemo;
lblContents: TLabel;
btnLowerCase: TButton;
procedure btnUpperCaseClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btnLowerCaseClick(Sender: TObject);
public
UCase: Boolean;
procedure ChangeFileCase;
end; var
MainForm: TMainForm; implementation {$R *.DFM} procedure TMainForm.btnUpperCaseClick(Sender: TObject);
begin
UCase := True;
ChangeFileCase;
end; procedure TMainForm.btnLowerCaseClick(Sender: TObject);
begin
UCase := False;
ChangeFileCase;
end; procedure TMainForm.FormCreate(Sender: TObject);
begin
memTextContents.Lines.LoadFromFile(FName);
// Change to upper case by default.
UCase := True;
end; procedure TMainForm.ChangeFileCase;
var
FFileHandle: THandle; // Handle to the open file.
FMapHandle: THandle; // Handle to a file-mapping object
FFileSize: Integer; // Variable to hold the file size.
FData: PByte; // Pointer to the file's data when mapped.
PData: PChar; // Pointer used to reference the file data.
begin { First obtain a file handle to the file to be mapped. This code
assumes the existence of the file. Otherwise, you can use the
FileCreate() function to create a new file. } if not FileExists(FName) then
raise Exception.Create('File does not exist.')
else
FFileHandle := FileOpen(FName, fmOpenReadWrite); // If CreateFile() was not successful, raise an exception
if FFileHandle = INVALID_HANDLE_VALUE then
raise Exception.Create('Failed to open or create file'); try
{ Now obtain the file size which we will pass to the other file-
mapping functions. We'll make this size one byte larger as we
need to append a null-terminating character to the end of the
mapped-file's data.}
FFileSize := GetFileSize(FFileHandle, Nil); { Obtain a file-mapping object handle. If this function is not
successful, then raise an exception. }
FMapHandle := CreateFileMapping(FFileHandle, nil,
PAGE_READWRITE, 0, FFileSize, nil); if FMapHandle = 0 then
raise Exception.Create('Failed to create file mapping');
finally
// Release the file handle
CloseHandle(FFileHandle);
end; try
{ Map the file-mapping object to a view. This will return a pointer
to the file data. If this function is not successful, then raise
an exception. }
FData := MapViewOfFile(FMapHandle, FILE_MAP_ALL_ACCESS, 0, 0, FFileSize); if FData = Nil then
raise Exception.Create('Failed to map view of file'); finally
// Release the file-mapping object handle
CloseHandle(FMapHandle);
end; try
{ !!! Here is where you would place the functions to work with
the mapped file's data. For example, the following line forces
all characters in the file to uppercase }
PData := PChar(FData);
// Position the pointer to the end of the file's data
inc(PData, FFileSize); // Append a null-terminating character to the end of the file's data
PData^ := #0; // Now set all characters in the file to uppercase
if UCase then
StrUpper(PChar(FData))
else
StrLower(PChar(FData)); finally
// Release the file mapping.
UnmapViewOfFile(FData);
end;
memTextContents.Lines.Clear;
memTextContents.Lines.LoadFromFile(FName);
end; end.

Using a DLL with Shared Memory

//ShareLib.dpr
{
Copyright ?1999 by Delphi 5 Developer's Guide - Xavier Pacheco and Steve Teixeira
} library ShareLib; uses
ShareMem,
Windows,
SysUtils,
Classes;
const cMMFileName: PChar = 'SharedMapData'; {$I DLLDATA.INC} var
GlobalData : PGlobalDLLData;
MapHandle : THandle; { GetDLLData will be the exported DLL function }
procedure GetDLLData(var AGlobalData: PGlobalDLLData); StdCall;
begin
{ Point AGlobalData to the same memory address referred to by GlobalData. }
AGlobalData := GlobalData;
end; procedure OpenSharedData;
var
Size: Integer;
begin
{ Get the size of the data to be mapped. }
Size := SizeOf(TGlobalDLLData); { Now get a memory-mapped file object. Note the first parameter passes
the value $FFFFFFFF or DWord(-1) so that space is allocated from the system's
paging file. This requires that a name for the memory-mapped
object get passed as the last parameter. } MapHandle := CreateFileMapping(DWord(-1), nil, PAGE_READWRITE, 0, Size, cMMFileName); if MapHandle = 0 then
RaiseLastWin32Error;
{ Now map the data to the calling process's address space and get a
pointer to the beginning of this address }
GlobalData := MapViewOfFile(MapHandle, FILE_MAP_ALL_ACCESS, 0, 0, Size);
{ Initialize this data }
GlobalData^.S := 'ShareLib';
GlobalData^.I := 1;
if GlobalData = nil then
begin
CloseHandle(MapHandle);
RaiseLastWin32Error;
end;
end; procedure CloseSharedData;
{ This procedure un-maps the memory-mapped file and releases the memory-mapped
file handle }
begin
UnmapViewOfFile(GlobalData);
CloseHandle(MapHandle);
end; procedure DLLEntryPoint(dwReason: DWord);
begin
case dwReason of
DLL_PROCESS_ATTACH: OpenSharedData;
DLL_PROCESS_DETACH: CloseSharedData;
end;
end; exports
GetDLLData; begin
{ First, assign the procedure to the DLLProc variable }
DllProc := @DLLEntryPoint;
{ Now invoke the procedure to reflect that the DLL is attaching
to the process }
DLLEntryPoint(DLL_PROCESS_ATTACH);
end.

App1:

//App1.dpr
{
Copyright ?1999 by Delphi 5 Developer's Guide - Xavier Pacheco and Steve Teixeira
} unit MainFrmA1; interface uses
Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, StdCtrls, ExtCtrls, Mask; {$I DLLDATA.INC} type TMainForm = class(TForm)
edtGlobDataStr: TEdit;
btnGetDllData: TButton;
meGlobDataInt: TMaskEdit;
procedure btnGetDllDataClick(Sender: TObject);
procedure edtGlobDataStrChange(Sender: TObject);
procedure meGlobDataIntChange(Sender: TObject);
procedure FormCreate(Sender: TObject);
public
GlobalData: PGlobalDLLData;
end; var
MainForm: TMainForm; { Define the DLL's exported procedure }
procedure GetDLLData(var AGlobalData: PGlobalDLLData); StdCall External 'SHARELIB.DLL'; implementation {$R *.DFM} procedure TMainForm.btnGetDllDataClick(Sender: TObject);
begin
{ Get a pointer to the DLL's data }
GetDLLData(GlobalData);
{ Now update the controls to reflect GlobalData's field values }
edtGlobDataStr.Text := GlobalData^.S;
meGlobDataInt.Text := IntToStr(GlobalData^.I);
end; procedure TMainForm.edtGlobDataStrChange(Sender: TObject);
begin
{ Update the DLL data with the changes }
GlobalData^.S := edtGlobDataStr.Text;
end; procedure TMainForm.meGlobDataIntChange(Sender: TObject);
begin
{ Update the DLL data with the changes }
if meGlobDataInt.Text = EmptyStr then
meGlobDataInt.Text := '0';
GlobalData^.I := StrToInt(meGlobDataInt.Text);
end; procedure TMainForm.FormCreate(Sender: TObject);
begin
btnGetDllDataClick(nil);
end; end.

App2:

//App2.dpr
{
Copyright ?1999 by Delphi 5 Developer's Guide - Xavier Pacheco and Steve Teixeira
} unit MainFrmA2; interface uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls; {$I DLLDATA.INC} type TMainForm = class(TForm)
lblGlobDataStr: TLabel;
tmTimer: TTimer;
lblGlobDataInt: TLabel;
procedure tmTimerTimer(Sender: TObject);
public
GlobalData: PGlobalDLLData;
end; { Define the DLL's exported procedure }
procedure GetDLLData(var AGlobalData: PGlobalDLLData); StdCall External 'SHARELIB.DLL'; var
MainForm: TMainForm; implementation {$R *.DFM} procedure TMainForm.tmTimerTimer(Sender: TObject);
begin
GetDllData(GlobalData); // Get access to the data
{ Show the contents of GlobalData's fields.}
lblGlobDataStr.Caption := GlobalData^.S;
lblGlobDataInt.Caption := IntToStr(GlobalData^.I);
end; end.

  

Delphi Memory-Mapped File简单示例的更多相关文章

  1. 虚拟内存(VirtualAlloc),堆(HeapAlloc/malloc/new)和Memory Mapped File

    http://blog.csdn.net/zj510/article/details/39400087 内存管理有三种方式: 1. 虚拟内存,VirtualAlloc之类的函数 2. 堆,Heapxx ...

  2. C# .Net 多进程同步 通信 共享内存 内存映射文件 Memory Mapped 转 VC中进程与进程之间共享内存 .net环境下跨进程、高频率读写数据 使用C#开发Android应用之WebApp 分布式事务之消息补偿解决方案

    C# .Net 多进程同步 通信 共享内存 内存映射文件 Memory Mapped 转 节点通信存在两种模型:共享内存(Shared memory)和消息传递(Messages passing). ...

  3. ACEXML解析XML文件——简单示例程序

    掌握了ACMXML库解析XML文件的方法后,下面来实现一个比较完整的程序. 定义基本结构 xml文件格式如下 <?xml version="1.0"?> <roo ...

  4. 非刚性图像配准 matlab简单示例 demons算法

    2011-05-25 17:21 非刚性图像配准 matlab简单示例 demons算法, % Clean clc; clear all; close all; % Compile the mex f ...

  5. lucene创建索引简单示例

    利用空闲时间写了一个使用lucene创建索引简单示例, 1.使用maven创建的项目 2.需要用到的jar如下: 废话不多说,直接贴代码如下: 1.创建索引的类(HelloLucene): packa ...

  6. C# .Net 多进程同步 通信 共享内存 内存映射文件 Memory Mapped 转

    原文:C# .Net 多进程同步 通信 共享内存 内存映射文件 Memory Mapped 转 节点通信存在两种模型:共享内存(Shared memory)和消息传递(Messages passing ...

  7. Java调度框架Quartz简单示例

    Quartz的大名如雷贯耳,这里就不赘述,而且本文也不作为深入探讨,只是看完Quartz的官方文档后,下个简单示例,至少证明曾经花了点时间学习过,以备不时之需. Quartz使用了SLF4J,所以至少 ...

  8. C++ 设计模式 依赖倒置原则 简单示例

    C++ 设计模式 依赖倒置原则 简单示例 /** * 依赖倒置原则(Dependency Inversion Principle) * 依赖于抽象(接口),不要依赖具体的实现(类),也就是针对接口编程 ...

  9. ajaxFileUpload上传文件简单示例

    写在前面: 上传文件的方式有很多,最近在做项目的时候,一开始也试用了利用jquery的插件ajaxFileUpload来上传大文件,下面,用一个上传文件的简单例子,记录下,学习的过程~~~ 还是老样子 ...

随机推荐

  1. mysql的统计函数

    一:统计函数 MySQL提供5个统计函数来对对数据进行统计.分别是实现对记录进行统计数,计算和,计算平均数,计算最大值和计算最小值. 1. 统计数据记录条数 可以有两种方式: COUNT(*)使用方式 ...

  2. C# params参数的应用

    为了将方法声明为可以接受可变数量参数的方法,我们可以使用params关键字来声明数组,如下所示: public static Int32Add(params Int32[] values) { Int ...

  3. HDU 1180 (BFS搜索)

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1180 题目大意:迷宫中有一堆楼梯,楼梯横竖变化.这些楼梯在奇数时间会变成相反状态,通过楼梯会顺便到达 ...

  4. 使用CSS 3创建不规则图形 文字围绕

    前言 CSS 创建复杂图形的技术即将会被广泛支持,并且应用到实际项目中.本篇文章的目的是为大家开启它的冰山一角.我希望这篇文章能让你对不规则图形有一个初步的了解. 现在,我们已经可以使用CSS 3 常 ...

  5. [leetCode][003] Intersection of Two Linked Lists

    [题目]: Write a program to find the node at which the intersection of two singly linked lists begins. ...

  6. 《菊与刀》--[美]鲁思·本尼迪克特(Ruth Benedict)

    <菊与刀>这本书实在是好看. 下面是一些书摘: * 由在美国曾经全力以赴与之战斗的敌人中,日本人的脾气是最琢磨不透的. * “菊”本是日本皇家家微,“刀”是武家文化的象征. * 日本人的格 ...

  7. myeclipse 8.5最新注册码

    myeclipse 8.5最新注册码(过期时间到2016年) Subscriber:huazai          Subscription Code:uLR8ZC-855550-6156585630 ...

  8. hdu Waiting ten thousand years for Love

    被这道题坑到了,如果单纯的模拟题目所给的步骤,就会出现同一个位置要走两次的情况...所以对于bfs来说会很头痛. 第一个代码是wa掉的代码,经过调试才知道这个wa的有点惨,因为前面的操作有可能会阻止后 ...

  9. cmd下常用的一些命令

    1.calc计算器 2.Mspaint画图 3.Netstat -anb查看端口 输入netstat -anb时可能会遇到下面问题 只要到搜索框输入cmd,然后到其快捷方式上右击以管理员身份运行即可 ...

  10. 获取当前 Windows 的安装序列号

    Dim s s = InputBox("当前Windows系统序列号为:", "Windows序列号", GetWindowsSN) WScript.Quit ...