Day: May 31, 2013
VBA Internals: String Variables and Pointers in Depth
This is the next installment of a series of deep-dives into the structure and implementation of variables in Visual Basic for Applications. For the previous posts, see the following:
- What’s in a variable - Categories of variables in VBA, by implementation
- Getting Pointers - Overview of how to obtain pointers in VBA
- Scalar Variables and Pointers in Depth - Details of numeric scalar variables and pointers
In this post, I will cover the details of string variables and pointers. See Scalar Variables and Pointers in Depth for additional background and for the code for the utility functions HexPtr
and Mem_ReadHex
.
Pointers and memory for string variables
Even though string variables are treated semantically as value types, they are reference types by implementation. The contents of a string variable is actually a pointer to another memory location where the actual string characters are stored. With VBA we can either get the address to the variable itself using VarPtr
, or we can go straight to the start of the character buffer by using StrPtr
. For a variable declared as a String
, then, directly reading the memory at the address returned by VarPtr
should give you the same pointer value as calling StrPtr
.