如何在两个应用程序之间设置共享内存:(0分)

  • 主题发起人 主题发起人 netbug
  • 开始时间 开始时间
N

netbug

Unregistered / Unconfirmed
GUEST, unregistred user!
请看:<br>这个是发送消息的,<br>procedure TForm1.Button1Click(Sender: TObject);<br>var i,j:integer;p1:^integer;<br>begin<br>&nbsp;i:=findwindow(nil,'form2');<br>&nbsp;j:=34;<br>&nbsp;p1:=@j;<br>&nbsp;sendmessage(i,wm_user,integer(p1),0);<br>end;<br>与接受消息的,<br>procedure mymessage1(var i:Tmessage);message wm_user;<br>....<br>procedure tform2.mymessage1(var i:Tmessage);<br>&nbsp;var j:integer; t:^integer;<br>&nbsp;begin<br>&nbsp;j:=i.wparam;<br>&nbsp;t:=ptr(j);<br>&nbsp;edit1.text:=inttostr(wm_user);<br>&nbsp;edit2.Text:=inttostr(t^);<br>end;<br>我发现在发送方的integer(p1)与接受方的i.wparam是一样的,<br>这说明发送方与接受方在传递整数时是可以传递的,但发送<br>方的j与接受方t^就不同了,这说明发送方j的地址到了接受<br>方时并未受到保护,我想用没有办法在俩个程序之间设置<br>个共享内存区(我只是想做个测试,因为如想传递整数,<br>可以直接传递),请问:有什么办法可以设置共享内存?<br>谢谢。<br>
 
可用 FileStream 或 Mutex。
 
最方便的是CreateFileMapping,传什么都行
 
怎么有人看到没分给就不啃气了。<br>这种风气不好吧?!
 
没分当然不啃气啦,我上网都要花不少钱呢
 
First create a share memory.<br><br>1. CreateFileMapping &nbsp;// Create a file mapping<br>2. MapViewOfFile &nbsp; &nbsp; &nbsp;// Get pointer of this file mapping<br><br>Access this memory at other process<br><br>1. OpenFileMapping &nbsp; // Open a file mapping<br>2. MapViewOfFile &nbsp; &nbsp; // Get a pointer of file mapping, you can access<br>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// this memory<br><br>enjoy it.
 
其它地方看到的,我试验过了,OK。<br><br>&nbsp; private<br>&nbsp; &nbsp; hMapFile: THandle;<br>&nbsp; &nbsp; MapFilePointer: Pointer;<br>&nbsp; public<br>&nbsp; &nbsp; { Public declarations }<br>&nbsp; end;<br>var<br>&nbsp; Form1: TForm1;<br>implementation<br>{$R *.DFM}<br>procedure TForm1.FormCreate(Sender: TObject);<br>begin<br>&nbsp; hMapFile := CreateFileMapping (<br>&nbsp; &nbsp; $FFFFFFFF, // 特殊内存映射句柄<br>&nbsp; &nbsp; nil, page_ReadWrite, 0,10000, <br>&nbsp; &nbsp; 'DdhDemoMappedFile'); // 文件名<br>&nbsp; if hMapFile &lt;&gt; 0 then<br>&nbsp; &nbsp; MapFilePointer := MapViewOfFile (<br>&nbsp; &nbsp; &nbsp; hMapFile, // 上面映象文件的句柄<br>&nbsp; &nbsp; &nbsp; File_Map_All_Access, <br>&nbsp; &nbsp; &nbsp; 0, 0, 0) // 访问整个映象文件<br>&nbsp; else<br>&nbsp; &nbsp; ShowMessage ('hMapFile = 0');<br>&nbsp; if MapFilePointer = nil then<br>&nbsp; &nbsp; ShowMessage ('MapFilePointer = nil');<br>end;<br><br>procedure TForm1.BtnWriteClick(Sender: TObject);<br>begin<br>&nbsp; StrCopy (PChar (MapFilePointer),<br>&nbsp; &nbsp; PChar (EditWrite.Text));//把内容写入共享内存<br>end;<br><br>procedure TForm1.BtnReadClick(Sender: TObject);<br>var<br>&nbsp; S: string;<br>begin<br>&nbsp; S := PChar (MapFilePointer);//从共享内存读出内容<br>&nbsp; EditRead.Text := S;<br>end;<br>用这种方法,不但可以在不同的程序之间共享数据,还可以<br>在同一程序的不同实例间共享数据。为了及时通知其它进程<br>共享数据的变化,可以自定义一条用户消息,通过发消息来<br>实现。<br>
 
接受答案了.
 

Similar threads

S
回复
0
查看
3K
SUNSTONE的Delphi笔记
S
S
回复
0
查看
2K
SUNSTONE的Delphi笔记
S
D
回复
0
查看
1K
DelphiTeacher的专栏
D
后退
顶部