此处所列的文章均是我自己从国外的网站摘抄并翻译的,由于英文水平有限,里面肯定有不少错漏.翻译这些东西没有其他的什么用途,只是提高自己的英语阅读能力和编程技术水平而已     

文件流3

function FileOpen(const FileName: string; Mode: LongWord): Integer;
{$IFDEF MSWINDOWS}
const
  AccessMode: array[0..2] of LongWord = (
    GENERIC_READ,   //DWORD($80000000);
    GENERIC_WRITE,  //$40000000;
    GENERIC_READ or GENERIC_WRITE);
  ShareMode: array[0..4] of LongWord = (
    0,
    0,
    FILE_SHARE_READ, //$00000001;
    FILE_SHARE_WRITE, //$00000002;
    FILE_SHARE_READ or FILE_SHARE_WRITE);//$00000003;
begin
{
  fmOpenRead       = $0000;
  fmOpenWrite      = $0001;
  fmOpenReadWrite  = $0002;
  }
  Result := -1;
  if ((Mode and 3) <= fmOpenReadWrite) and
    ((Mode and $F0) <= fmShareDenyNone) then
    Result := Integer(CreateFile(PChar(FileName), AccessMode[Mode and 3],
      ShareMode[(Mode and $F0) shr 4], nil, OPEN_EXISTING,
      FILE_ATTRIBUTE_NORMAL, 0));
end;

内存流的操作,把一个内存流保存到另一个流中或文件中。

var
  MemoryStream: TMemoryStream;
  StrStream: TStringStream;
begin
  MemoryStream := TMemoryStream.Create;
  StrStream := TStringStream.Create('');
  StrStream.WriteString('我靠');
  StrStream.WriteString('你来了');
  StrStream.Seek(0, 0);
//  MemoryStream.LoadFromFile('c:\KKK.txt');
//  MemoryStream.LoadFromFile('c:\Info.txt');
  MemoryStream.CopyFrom(StrStream, StrStream.Size);
  MemoryStream.SaveToStream(StrStream);
  MemoryStream.SaveToFile('c:\KKK.txt');

 

procedure TForm1.Button2Click(Sender: TObject);
var
  hHeap: THandle;
  iSize, i: Integer;
  Ps: Pchar;
begin
  hHeap := GlobalAlloc(GMEM_MOVEABLE, 1000);
  iSize := GlobalSize(hHeap);
  caption := IntToStr(iSize);
  Ps := GlobalLock(hHeap);
  for i := 0 to 1000 do
  Begin
    ps[i] := '1';
  end;
  ShowMessage(ps);
  GlobalUnlock(hHeap);
  GlobalFree(hHeap);
end;

 

Windows Memory Management
Note: Major portions of this document came from the Visual C++ online help

Win16
The 16-bit Windows memory management is modeled after a 'handle' method, designed to implement virtual memory management in a non-preemptive operating environment. Under Win16, programs are written to follow a 'well-behaved' guideline when dealing with dynamic memory, which is:

  •  
    • 1. Allocate a handle for a block of memory
      2. Lock the handle to actually get the memory, only when needed
      3. Unlock the handle when the memory won't be needed for a while
      4. Free the handle when the memory won't be needed anymore


Since Win16 used a handle method, using the malloc/new memory management routines was considered a poor practice. In Win16, programs had access to two heaps: Global and Local. The global heap was larger, and is accessible by other programs (programs could share memory, like in DDE), while the local heap was smaller, and accessible only to the single program.

Allocating a handle
There are two functions used to allocate a handle for a block of memory, they are GlobalAlloc, and LocalAlloc. GlobalAlloc provides memory from a global allocation heap, which can be shared between two programs, while LocalAlloc does not. In Win16, these functions do not really allocate memory, but in Win32 they do.

HGLOBAL GlobalAlloc( UINT uFlags, DWORD dwBytes );

uFlags
Specifies how to allocate memory. If zero is specified, the default is GMEM_FIXED. Except for the incompatible combinations that are specifically noted, any combination of the following flags can be used. To indicate whether the function allocates fixed or movable memory, specify one of the first four flags:

Flag Meaning
GMEM_FIXED Allocates fixed memory. This flag cannot be combined with the GMEM_MOVEABLE or GMEM_DISCARDABLE flag. The return value is a pointer to the memory block. To access the memory, the calling process simply casts the return value to a pointer.
GMEM_MOVEABLE Allocates movable memory. This flag cannot be combined with the GMEM_FIXED flag. The return value is the handle of the memory object. The handle is a 32-bit quantity that is private to the calling process. To translate the handle into a pointer, use the GlobalLock function.
GPTR Combines the GMEM_FIXED and GMEM_ZEROINIT flags.
GHND Combines the GMEM_MOVEABLE and GMEM_ZEROINIT flags.
GMEM_DDESHARE Allocates memory to be used by the dynamic data exchange (DDE) functions for a DDE conversation. Unlike Windows version 3. x, this memory is not shared globally. However, this flag is available for compatibility purposes. It may be used by some applications to enhance the performance of DDE operations and should, therefore, be specified if the memory is to be used for DDE. Only processes that use DDE or the clipboard for interprocess communications should specify this flag.
GMEM_DISCARDABLE Allocates discardable memory. This flag cannot be combined with the GMEM_FIXED flag. Some Win32-based applications may ignore this flag.
GMEM_LOWER Ignored. This flag is provided only for compatibility with Windows version 3. x.
GMEM_NOCOMPACT Does not compact or discard memory to satisfy the allocation request.
GMEM_NODISCARD Does not discard memory to satisfy the allocation request.
GMEM_NOT_BANKED Ignored. This flag is provided only for compatibility with Windows version 3. x.
GMEM_NOTIFY Ignored. This flag is provided only for compatibility with Windows version 3. x.
GMEM_SHARE Same as the GMEM_DDESHARE flag.
GMEM_ZEROINIT Initializes memory contents to zero.

 

dwBytes
Specifies the number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies the GMEM_MOVEABLE flag, the function returns a handle to a memory object that is marked as discarded.

Return Values
If the function succeeds, the return value is the handle of the newly allocated memory object. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

The GlobalAlloc and LocalAlloc functions are limited to a combined total of 65,536 handles for GMEM_MOVEABLE and LMEM_MOVEABLE memory per process. This limitation does not apply to GMEM_FIXED or LMEM_FIXED memory.

If this function succeeds, it allocates at least the amount of memory requested. If the actual amount allocated is greater than the amount requested, the process can use the entire amount. To determine the actual number of bytes allocated, use the GlobalSize function.

LocalAlloc
The LocalAlloc function allocates the specified number of bytes from the heap. In the linear Win32 API environment, there is no difference between the local heap and the global heap.

HLOCAL LocalAlloc(UINT uFlags, UINT uBytes );

uFlags
Specifies how to allocate memory. If zero is specified, the default is the LMEM_FIXED flag. Except for the incompatible combinations that are specifically noted, any combination of the following flags can be specified. To indicate whether the function allocates fixed or movable memory, specify one of the first six flags:

Flag Meaning
LMEM_FIXED Allocates fixed memory. This flag cannot be combined with the LMEM_MOVEABLE or LMEM_DISCARDABLE flag. The return value is a pointer to the memory block. To access the memory, the calling process simply casts the return value to a pointer.
LMEM_MOVEABLE Allocates movable memory. This flag cannot be combined with the LMEM_FIXED flag. The return value is the handle of the memory object. The handle is a 32-bit quantity that is private to the calling process. To translate the handle into a pointer, use the LocalLock function.
LPTR Combines the LMEM_FIXED and LMEM_ZEROINIT flags.
LHND Combines the LMEM_MOVEABLE and LMEM_ZEROINIT flags.
NONZEROLHND Same as the LMEM_MOVEABLE flag.
NONZEROLPTR Same as the LMEM_FIXED flag.
LMEM_DISCARDABLE Allocates discardable memory. This flag cannot be combined with the LMEM_FIXED flag. Some Win32-based applications may ignore this flag.
LMEM_NOCOMPACT Does not compact or discard memory to satisfy the allocation request.
LMEM_NODISCARD Does not discard memory to satisfy the allocation request.
LMEM_ZEROINIT Initializes memory contents to zero.



uBytes
Specifies the number of bytes to allocate. If this parameter is zero and the uFlags parameter specifies the LMEM_MOVEABLE flag, the function returns a handle to a memory object that is marked as discarded.

Return Values
If the function succeeds, the return value is the handle of the newly allocated memory object. If the function fails, the return value is NULL. To get extended error information, call GetLastError.


Locking a handle
Once a handle was obtained, the GlobalLock or LocalLock function is called to actually 'lock' the memory, and return a pointer to it. Both functions have a similar calling format and return value:

LPVOID GlobalLock( HGLOBAL hMem );
LPVOID LocalLock( HLOCAL hMem );

hMem identifies the handle to be locked. Each function returns a pointer to the memory block, or NULL upon failure.

In the case of a globally-allocated, GMEM_FIXED memory block, GloclLock will return the same value as the handle.


Unlocking a handle
A handle is unlocked with either the GlobalUnlock or LocalUnlock functions.

BOOL GlobalUnlock( HGLOBAL hMem );
BOOL LocalUnlock( HLOCAL hMem );

hMem identifies the handle to be unlocked. Since the handle maintains a lock count, if these functions are called on a block, and the lock count is not decremented to zero, then it's return value is non-zero. If the block of memory is succesfully released (it's count was 1), then it returns 0.


Other memory-management functions include: GlobalRealloc, LocalRealloc, GlobalFlags, and LocalFlags.


Moveable, Discardable, and Fixed
Moveable means that a block may be moved in memory during a heap compaction to another memory location. Discardable means that a block may be stored to disk and retrieve later, when needed again. Locked memory blocks are not moved or discarded. A Fixed memory block will never be moved or discarded.




Win32
Win32 in Win95 and NT introduce real virtual memory. The operating systems now takes care of this automatically, and stores information to disk as needed. In Win32 programming, each program receives 2 gigabytes of virtual memory, which the operating system manages.

One particularly import change here, is that there is no longer a need to lock and unlock handles. The primary functions are VirtualAlloc and VirtualFree. Other memory management routines such as GlobalAlloc, GlobalLock, GlobalFree, malloc, free, new, and delete, have all been changed to use VirtualAlloc and VirtualFree at a low level. This means that under Win32, is now acceptable to use the ANSI standard routines malloc and new to allocate a block of memory.

Unlike Win16, Win32 does not have a global and locl heap, the heap is a single resource.


Allocating memory
The VirtualAlloc function reserves or commits a region of pages in the virtual address space of the calling process. Memory allocated by this function is automatically initialized to zero.

LPVOID VirtualAlloc( LPVOID lpAddress, DWORD dwSize, DWORD flAllocationType,
DWORD flProtect );

lpAddress
Specifies the desired starting address of the region to allocate. If the memory is being reserved, the specified address is rounded down to the next 64-kilobyte boundary. If the memory is already reserved and is being committed, the address is rounded down to the next page boundary. To determine the size of a page on the host computer, use the GetSystemInfo function. If this parameter is NULL, the system determines where to allocate the region.

dwSize
Specifies the size, in bytes, of the region. If the lpAddress parameter is NULL, this value is rounded up to the next page boundary. Otherwise, the allocated pages include all pages containing one or more bytes in the range from lpAddress to (lpAddress+dwSize). This means that a 2-byte range straddling a page boundary causes both pages to be included in the allocated region.

flAllocationType
Specifies the type of allocation. You can specify any combination of the following flags:

Flag Meaning
MEM_COMMIT Allocates physical storage in memory or in the paging file on disk for the specified region of pages.

An attempt to commit an already committed page will not cause the function to fail. This means that a range of committed or decommitted pages can be committed without having to worry about a failure.
MEM_RESERVE Reserves a range of the process's virtual address space without allocating any physical storage. The reserved range cannot be used by any other allocation operations (the malloc function, the LocalAlloc function, and so on) until it is released. Reserved pages can be committed in subsequent calls to the VirtualAlloc function.
MEM_TOP_DOWN Allocates memory at the highest possible address.

 

flProtect
Specifies the type of access protection. If the pages are being committed, any one of the following flags can be specified, along with the PAGE_GUARD and PAGE_NOCACHE protection modifier flags, as desired:

Flag Meaning
PAGE_READONLY Enables read access to the committed region of pages. An attempt to write to the committed region results in an access violation. If the system differentiates between read-only access and execute access, an attempt to execute code in the committed region results in an access violation.
PAGE_READWRITE Enables both read and write access to the committed region of pages.
PAGE_EXECUTE Enables execute access to the committed region of pages. An attempt to read or write to the committed region results in an access violation.
PAGE_EXECUTE_READ Enables execute and read access to the committed region of pages. An attempt to write to the committed region results in an access violation.
PAGE_EXECUTE_READWRITE Enables execute, read, and write access to the committed region of pages.
PAGE_GUARD Pages in the region become guard pages. Any attempt to read from or write to a guard page causes the operating system to raise a STATUS_GUARD_PAGE exception and turn off the guard page status. Guard pages thus act as a one-shot access alarm.

The PAGE_GUARD flag is a page protection modifier. An application uses it with one of the other page protection flags, with one exception: It cannot be used with PAGE_NOACCESS. When an access attempt leads the operating system to turn off guard page status, the underlying page protection takes over.

If a guard page exception occurs during a system service, the service typically returns a failure status indicator.
PAGE_NOACCESS Disables all access to the committed region of pages. An attempt to read from, write to, or execute in the committed region results in an access violation exception, called a general protection (GP) fault.
PAGE_NOCACHE Allows no caching of the committed regions of pages. The hardware attributes for the physical memory should be specified as "no cache." This is not recommended for general usage. It is useful for device drivers; for example, mapping a video frame buffer with no caching. This flag is a page protection modifier, only valid when used with one of the page protections other than PAGE_NOACCESS.



Return Values
If the function succeeds, the return value is the base address of the allocated region of pages. If the function fails, the return value is NULL. To get extended error information, call GetLastError.

Remarks
VirtualAlloc can perform the following operations:

· Commit a region of pages reserved by a previous call to the VirtualAlloc function.
· Reserve a region of free pages.
· Reserve and commit a region of free pages.


You can use VirtualAlloc to reserve a block of pages and then make additional calls to VirtualAlloc to commit individual pages from the reserved block. This enables a process to reserve a range of its virtual address space without consuming physical storage until it is needed.

Each page in the process's virtual address space is in one of three states:

State Meaning
Free The page is not committed or reserved and is not accessible to the process. VirtualAlloc can reserve, or simultaneously reserve and commit, a free page.
Reserved The range of addresses cannot be used by other allocation functions, but the page is not accessible and has no physical storage associated with it. VirtualAlloc can commit a reserved page, but it cannot reserve it a second time. The VirtualFree function can release a reserved page, making it a free page.
Committed Physical storage is allocated for the page, and access is controlled by a protection code. The system initializes and loads each committed page into physical memory only at the first attempt to read or write to that page. When the process terminates, the system releases the storage for committed pages. VirtualAlloc can commit an already committed page. This means that you can commit a range of pages, regardless of whether they have already been committed, and the function will not fail. VirtualFree can decommit a committed page, releasing the page's storage, or it can simultaneously decommit and release a committed page.



If the lpAddress parameter is not NULL, the function uses the lpAddress and dwSize parameters to compute the region of pages to be allocated. The current state of the entire range of pages must be compatible with the type of allocation specified by the flAllocationType parameter. Otherwise, the function fails and none of the pages are allocated. This compatibility requirement does not preclude committing an already committed page; see the preceding list.

The PAGE_GUARD protection modifier flag establishes guard pages. Guard pages act as one-shot access alarms. See Guard Pages.


Locking virtual memory
The VirtualLock function locks the specified region of the process's virtual address space into memory, ensuring that subsequent access to the region will not incur a page fault.

BOOL VirtualLock( LPVOID lpAddress, DWORD dwSize );

lpAddress
Points to the base address of the region of pages to be locked.

dwSize
Specifies the size, in bytes, of the region to be locked. The region of affected pages includes all pages that contain one or more bytes in the range from the lpAddress parameter to (lpAddress+dwSize). This means that a 2-byte range straddling a page boundary causes both pages to be locked.

Return Values
If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks
All pages in the specified region must be committed. Memory protected with the PAGE_NOACCESS flag cannot be locked.

Locking pages into memory may degrade the performance of the system by reducing the available RAM and forcing the system to swap out other critical pages to the paging file. By default, a process can lock a maximum of 30 pages. The default limit is intentionally small to avoid severe performance degradation. Applications that need to lock larger numbers of pages must first call the SetProcessWorkingSetSize function to increase their minimum and maximum working set sizes. The maximum number of pages that a process can lock is equal to the number of pages in its minimum working set minus a small overhead.

Pages that a process has locked remain resident even when the process is idle for extended periods.

To unlock a region of locked pages, use the VirtualUnlock function. Locked pages are automatically unlocked when the process terminates.

This function is not like the GlobalLock or LocalLock function in that it does not increment a lock count and translate a handle into a pointer. There is no lock count for virtual pages, so multiple calls to the VirtualUnlock function are never required to unlock a region of pages.

Windows 95:
On Windows 95, the VirtualLock function is implemented as a stub that has no effect and always returns TRUE.


Unlocking Virtual memory
Virtual memory is unlocked using the VirtualUnlock function:
BOOL VirtualUnlock(LPVOID lpAddress, DWORD dwSize );

lpAddress
Points to the base address of the region of pages to be unlocked.

dwSize
Specifies the size, in bytes, of the region being unlocked. The region of affected pages includes all pages containing one or more bytes in the range from the lpAddress parameter to (lpAddress+dwSize). This means that a 2-byte range straddling a page boundary causes both pages to be unlocked.

Return Values
If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks
For the function to succeed, the range specified need not match a range passed to a previous call to the VirtualLock function, but all pages in the range must be locked.


Freeing Virtual Memory
The VirtualFree function releases or decommits (or both) a region of pages within the virtual address space of the calling process.

BOOL VirtualFree( LPVOID lpAddress, DWORD dwSize, DWORD dwFreeType );

lpAddress
Points to the base address of the region of pages to be freed. If the dwFreeType parameter includes the MEM_RELEASE flag, this parameter must be the base address returned by the VirtualAlloc function when the region of pages was reserved.

dwSize
Specifies the size, in bytes, of the region to be freed. If the dwFreeType parameter includes the MEM_RELEASE flag, this parameter must be zero. Otherwise, the region of affected pages includes all pages containing one or more bytes in the range from the lpAddress parameter to (lpAddress+dwSize). This means that a 2-byte range straddling a page boundary causes both pages to be freed.

dwFreeType
Specifies the type of free operation. One, but not both, of the following flags can be specified:

Flag Meaning
MEM_DECOMMIT Decommits the specified region of committed pages.

An attempt to decommit an uncommitted page will not cause the function to fail. This means that a range of committed or uncommitted pages can be decommitted without having to worry about a failure.
MEM_RELEASE Releases the specified region of reserved pages. If this flag is specified, the dwSize parameter must be zero, or the function fails.

 

Return Values
If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks
VirtualFree can perform one of the following operations:

· Decommit a region of committed or uncommitted pages.
· Release a region of reserved pages.
· Decommit and release a region of committed or uncommitted pages.

To release a region of pages, the entire range of pages must be in the same state (all reserved or all committed) and the entire region originally reserved by the VirtualAlloc function must be released at the same time. If only part of the pages in the original reserved region are committed, you must first call VirtualFree to decommit the committed pages and then call VirtualFree again to release the entire block.

Pages that have been released are free pages available for subsequent allocation operations. Attempting to read from or write to a free page results in an access violation exception.

VirtualFree can decommit an uncommitted page; this means that a range of committed or uncommitted pages can be decommitted without having to worry about a failure. Decommitting a page releases its physical storage, either in memory or in the paging file on disk. If a page is decommitted but not released, its state changes to reserved, and it can be committed again by a subsequent call to VirtualAlloc. Attempting to read from or write to a reserved page results in an access violation exception.

The current state of the entire range of pages must be compatible with the type of free operation specified by the dwFreeType parameter. Otherwise, the function fails and no pages are released or decommitted.

posted @ 2010-11-14 20:09  AppleAndPear  阅读(266)  评论(0编辑  收藏  举报