PEEK and PEEK$ functions

Purpose

Return the byte (PEEK) or sequence of bytes (PEEK$) at a specified memory location.

Syntax

numvar = PEEK([datatype,] address???)

strvar = PEEK$([ASCIIZ,] address???, count&)

Remarks

The PEEK functions and complementary POKE statements are low-level methods of accessing individual bytes in memory.  The data is retrieved from memory, starting at the specified 32-bit address???.

PEEK retrieves a numeric value starting at a specified memory address.

PEEK$ retrieves count& consecutive bytes and returns them as a string, where the ASCII code of the first character of the string is the value of the first byte retrieved, the next ASCII code is the next byte retrieved, and so on.  If ASCIIZ is specified, PEEK$ reads successive characters from an ASCIIZ buffer of the specified size, until a terminating $NUL (CHR$(0)) byte is found.  Since ASCIIZ strings must contain a terminating $NUL, the maximum length of the returned string is 1 character less than the specified size.

datatype

The numeric data type to retrieve, which may be any one of BYTE, WORD, DWORD, INTEGER, LONG, QUAD, SINGLE, DOUBLE, EXT, CUR, CUX. If a data type is not specified, BYTE is assumed.

address???

A valid 32-bit memory address specifying the location in memory where data retrieval should begin.

count&

A numeric expression that specifies the number of consecutive bytes to be read from memory starting at address???.

Restrictions

If address??? (or any byte in the range covered by count&) references an invalid address (memory that is not allocated to the application), Windows will generate a General Protection Fault (GPF) and terminate the application.  GPFs cannot be trapped with an ON ERROR error handler.

See also

Pointers , POKE, STRPTR, VARPTR

Example

One common application for PEEK$ and POKE$ is to perform fast array and memory block copy operations by simply copying the entire block of memory which contains the array data, rather than storing each element individually with an assignment statement:

Elements& = 2000  ' 2000 elements in each array

DIM OriginalArray%(1 TO Elements&)

DIM NewArray%(1 TO Elements&)

 

'Method 1: assign each element individually

FOR Index& = 1 TO Elements&

  NewArray%(Index&) = OriginalArray%(Index&)

NEXT Index&

 

'Method 2: block copy with PEEK$ and POKE$ (faster)

Source&   = VARPTR(OriginalArray%(1))

Dest&     = VARPTR(NewArray%(1))

ArrayLen& = Elements& * 2     'byte length of array

POKE$ Dest&, PEEK$(Source&, ArrayLen&)  'copy block