An example of using a private heap:Unit unit1;
Interface
Uses
Windows, messages, sysutils, variants, classes, graphics, controls, forms,
Dialogs, stdctrls;
Type
Tform1 = Class (tform)
Button1: tbutton;
Procedure button1click (Sender: tobject );
End;
VaR
Form1: tform1;
Implementation
{$ R *. DFM}
VaR
Myheap: thandle; {heap handle}
P: pointer;
Procedure tform1.button1click (Sender: tobject );
VaR
I, num: integer;
P2: pointer;
STR: string;
Begin
{Create heap}
Myheap: = heapcreate (heap_zero_memory, 1024*1024*2, 0); {create a 2 m heap}
If myheap = 0 Then exit; {exit if creation fails}
{Allocate memory from the heap}
P: = heapalloc (myheap, 0, 7 );
If P = nil then exit; {exit with an error}
{Get memory block size}
Num: = heapsize (myheap, 0, P );
{Assign values to each byte of the memory block}
P2: = P;
For I: = 0 to num-1 do
Begin
Byte (P2 ^): = I + 65;
P2: = PTR (INTEGER (P2) + 1 );
End;
{Value}
P2: = P;
STR: = '';
For I: = 0 to num-1 do
Begin
STR: = STR + CHR (byte (P2 ^ ));
P2: = PTR (INTEGER (P2) + 1 );
End;
{Display memory block content and size}
Showmessagefmt ('% s, % d', [STR, num]); {abcdefg, 7}
//////////////////////////////////////// /////////////
{Memory expansion, this is a different sentence. The above code is repeated below}
P: = heaprealloc (myheap, 0, P, 26 );
If P = nil then exit; {exit with an error}
{Get memory block size}
Num: = heapsize (myheap, 0, P );
{Assign values to each byte of the memory block}
P2: = P;
For I: = 0 to num-1 do
Begin
Byte (P2 ^): = I + 65;
P2: = PTR (INTEGER (P2) + 1 );
End;
{Value}
P2: = P;
STR: = '';
For I: = 0 to num-1 do
Begin
STR: = STR + CHR (byte (P2 ^ ));
P2: = PTR (INTEGER (P2) + 1 );
End;
{Display memory block content and size}
Showmessagefmt ('% s, % d', [STR, num]); {abcdefghijklmnopqrstuvwxyz, 26}
//////////////////////////////////////// /////////////
{Release memory}
Heapfree (myheap, 0, P );
{Destroy heap}
Heapdestroy (myheap );
End;