Using OFFSET

From QB64 Wiki
Revision as of 16:08, 22 September 2011 by imported>Clippy (Created page with '{{small|By Michael Calkins}} An '''_OFFSET''' means a pointer. Use it any time that you need to pass or receive a pointer. With the API, types that start with P or LP, and param…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
By Michael Calkins

An _OFFSET means a pointer. Use it any time that you need to pass or receive a pointer. With the API, types that start with P or LP, and parameters that start with p or lp are generally pointers.


As for when to use the _OFFSET data type, it is basically any time that you need to pass a pointer to a function as a parameter, or have a pointer returned from a function as a return value. The _OFFSET type is basically the same as a void pointer in C. A pointer is a variable that holds a memory address. (I sometimes refer to the memory address itself as being a pointer, but usually, "pointer" means a variable that holds a memory address.) The symbol for a pointer in C is the asterisk, *, following some other type name.

So for example in C:

void * means a void pointer, that is, a pointer to a variable of any type.

Also, for example:

CHAR * means a pointer to a CHAR.


Example using QueryDosDeviceA to enumerate COM ports

'public domain, sept 2011, DECLARE DYNAMIC LIBRARY "kernel32" FUNCTION QueryDosDeviceA~& (BYVAL lpDeviceName AS _UNSIGNED _OFFSET, BYVAL lpTargetPath AS _UNSIGNED _OFFSET, BYVAL ucchMax AS _UNSIGNED LONG) FUNCTION GetLastError~& () END DECLARE DIM sizeofbuffer AS _UNSIGNED LONG DIM buffer AS STRING DIM i AS _UNSIGNED LONG DIM x AS _UNSIGNED LONG DIM n AS _UNSIGNED LONG sizeofbuffer = 1024 buffer = SPACE$(sizeofbuffer) DO x = 0 IF QueryDosDeviceA~&(0, _OFFSET(buffer), sizeofbuffer) = 0 THEN x = GetLastError~& IF x = &H7A THEN sizeofbuffer = sizeofbuffer + 1024 buffer = SPACE$(sizeofbuffer) ELSE PRINT "Error: 0x"; HEX$(x) END END IF END IF LOOP WHILE x = &H7A i = 1 n = 0 DO WHILE ASC(MID$(buffer, i, 1)) x = INSTR(i, buffer, CHR$(0)) PRINT MID$(buffer, i, x - i) IF MID$(buffer, i, 3) = "COM" THEN REDIM _PRESERVE comports(0 TO (n * 2) + 1) AS STRING comports(n * 2) = MID$(buffer, i, (x - i) + 1) n = n + 1 END IF i = x + 1 LOOP PRINT PRINT n; "COM ports:" IF n THEN FOR i = 0 TO n - 1 DO x = 0 IF QueryDosDeviceA~&(_OFFSET(comports(i * 2)), _OFFSET(buffer), sizeofbuffer) = 0 THEN x = GetLastError~& IF x = &H7A THEN sizeofbuffer = sizeofbuffer + 1024 buffer = SPACE$(sizeofbuffer) ELSE PRINT "Error: 0x"; HEX$(x) END END IF END IF LOOP WHILE x = &H7A comports((i * 2) + 1) = LEFT$(buffer, INSTR(buffer, CHR$(0)) - 1) comports(i * 2) = LEFT$(comports(i * 2), LEN(comports(i * 2)) - 1) PRINT CHR$(&H22); comports(i * 2); CHR$(&H22); " is mapped to: "; CHR$(&H22); comports((i * 2) + 1); CHR$(&H22) NEXT END IF buffer = "" END

See topic thread at forum