PEEK, PEEK$, and PEEK$$ functions  

Purpose

Returns a byte or sequence of bytes at a specified memory location.

Syntax

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

ansivar = PEEK$([STRINGZ,] address???, count&)

widevar = PEEK$$([WSTRINGZ,] 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.  If STRINGZ (or ASCIIZ) is specified, PEEK$ reads successive characters from memory, up to the specified size, until a terminating $NUL (CHR$(0)) byte is found.  Since STRINGZ strings must contain a terminating $NUL, the maximum length of the returned string is 1 character less than count&.

PEEK$$ retrieves count& consecutive 2-byte wide characters, and returns them as a wide character string.  If WSTRINGZ is specified, PEEK$$ reads successive characters from memory, up to the specified size, until a terminating $NUL (CHR$(0)) character is found.  Since WSTRINGZ strings must contain a terminating $NUL, the maximum length of the returned string is 1 character less than count&.

Contrary to intuitive notions, PEEK and POKE execute at the same high performance levels as pointer variables.  They offer an excellent alternative to pointers in many situations.

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 characters to be read from memory.

Restrictions

If address??? (or any memory 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