内存管理[4]
一個(gè)使用私有堆的例子:
unit Unit1;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls;typeTForm1 = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);end;varForm1: TForm1;implementation{$R *.dfm}varMyHeap: THandle; {堆句柄}p: Pointer;procedure TForm1.Button1Click(Sender: TObject); vari,num: Integer;p2: Pointer;str: string; begin{建立堆}MyHeap := HeapCreate(HEAP_ZERO_MEMORY, 1024*1024*2, 0); {建立個(gè) 2M 的堆}if Myheap = 0 then Exit; {如果創(chuàng)建失敗則退出}{從堆中分配內(nèi)存}p := HeapAlloc(MyHeap, 0, 7);if p = nil then Exit; {出錯(cuò)退出}{獲取內(nèi)存塊大小}num := HeapSize(MyHeap, 0, p);{給內(nèi)存塊的每個(gè)字節(jié)賦值}p2 := p;for i := 0 to num - 1 dobeginByte(p2^) := i + 65;p2 := Ptr(Integer(p2) + 1);end;{取值}p2 := p;str := '';for i := 0 to num - 1 dobeginstr := str + Chr(Byte(p2^));p2 := Ptr(Integer(p2) + 1);end;{顯示內(nèi)存塊的內(nèi)容與大小}ShowMessageFmt('%s,%d',[str,num]); {ABCDEFG,7}/{擴(kuò)充內(nèi)存, 只此一句不同, 下面都是重復(fù)上面的代碼}p := HeapReAlloc(MyHeap, 0, p, 26);if p = nil then Exit; {出錯(cuò)退出}{獲取內(nèi)存塊大小}num := HeapSize(MyHeap, 0, p);{給內(nèi)存塊的每個(gè)字節(jié)賦值}p2 := p;for i := 0 to num - 1 dobeginByte(p2^) := i + 65;p2 := Ptr(Integer(p2) + 1);end;{取值}p2 := p;str := '';for i := 0 to num - 1 dobeginstr := str + Chr(Byte(p2^));p2 := Ptr(Integer(p2) + 1);end;{顯示內(nèi)存塊的內(nèi)容與大小}ShowMessageFmt('%s,%d',[str,num]); {ABCDEFGHIJKLMNOPQRSTUVWXYZ,26}/{釋放內(nèi)存}HeapFree(MyHeap, 0, p);{銷毀堆}HeapDestroy(MyHeap); end;end.
unit Unit1;interfaceusesWindows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,Dialogs, StdCtrls;typeTForm1 = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);end;varForm1: TForm1;implementation{$R *.dfm}varMyHeap: THandle; {堆句柄}p: Pointer;procedure TForm1.Button1Click(Sender: TObject); vari,num: Integer;p2: Pointer;str: string; begin{建立堆}MyHeap := HeapCreate(HEAP_ZERO_MEMORY, 1024*1024*2, 0); {建立個(gè) 2M 的堆}if Myheap = 0 then Exit; {如果創(chuàng)建失敗則退出}{從堆中分配內(nèi)存}p := HeapAlloc(MyHeap, 0, 7);if p = nil then Exit; {出錯(cuò)退出}{獲取內(nèi)存塊大小}num := HeapSize(MyHeap, 0, p);{給內(nèi)存塊的每個(gè)字節(jié)賦值}p2 := p;for i := 0 to num - 1 dobeginByte(p2^) := i + 65;p2 := Ptr(Integer(p2) + 1);end;{取值}p2 := p;str := '';for i := 0 to num - 1 dobeginstr := str + Chr(Byte(p2^));p2 := Ptr(Integer(p2) + 1);end;{顯示內(nèi)存塊的內(nèi)容與大小}ShowMessageFmt('%s,%d',[str,num]); {ABCDEFG,7}/{擴(kuò)充內(nèi)存, 只此一句不同, 下面都是重復(fù)上面的代碼}p := HeapReAlloc(MyHeap, 0, p, 26);if p = nil then Exit; {出錯(cuò)退出}{獲取內(nèi)存塊大小}num := HeapSize(MyHeap, 0, p);{給內(nèi)存塊的每個(gè)字節(jié)賦值}p2 := p;for i := 0 to num - 1 dobeginByte(p2^) := i + 65;p2 := Ptr(Integer(p2) + 1);end;{取值}p2 := p;str := '';for i := 0 to num - 1 dobeginstr := str + Chr(Byte(p2^));p2 := Ptr(Integer(p2) + 1);end;{顯示內(nèi)存塊的內(nèi)容與大小}ShowMessageFmt('%s,%d',[str,num]); {ABCDEFGHIJKLMNOPQRSTUVWXYZ,26}/{釋放內(nèi)存}HeapFree(MyHeap, 0, p);{銷毀堆}HeapDestroy(MyHeap); end;end.
總結(jié)
- 上一篇: 水上遇险求救电话(水上遇险求救电话号是)
- 下一篇: AStar算法的原理及应用