Conventional wisdom:
In the latest version of VBA (VBA7),use the
LongPtr
type to represent pointers, which works on both 32 and 64-bit systems. In old versions of VBA, useLong
to represent pointers (assuming a 32-bit host, but this is a safe assumption as all 64-bit hosts use the latest version of VBA).
And what exactly is LongPtr? Well according to the VBA language reference:
LongPtr
(Long
integer on 32-bit systems,LongLong
integer on 64-bit systems)
Those two pieces of information confirm one fact: On 32-bit systems, pointers take 4 bytes and should be stored in a Long
, on 64-bit systems, pointers take 8 bytes and should be stored in a LongLong
and by extension, LongPtr
looks a bit like this under the hood:
#If Win64 Then
typedef LongPtr As LongLong
#Else
typedef LongPtr As Long
#End If
i.e. pointer size is linked directly to host bitness. In my experience this interpretation has always worked fine.
Problem
As pointed out in this question, pointers tend to be the same size as the bitness of the architecture. E.g. for a 32 bit program, pointers are 4 bytes, for a 64 bit program, pointers are 8 bytes. However there is no reason for this necessarily to be the case; a program with a 64-bit memory size may still use 32 bit pointers to navigate it.
That makes sense of you think about it. Just because my 64-bit program has used 8 byte chunks to split up its memory, doesn't mean I need 2^64 different possible pointers to navigate it. I may only have 16 bytes of memory in total, in which case my pointer could just be 1
or 0
!
So my questions:
- Are LongPtrs defined according to host bitness?
- If so, is there a reason that this is safe to do - is there something about VBA that means pointers will always match the size of the host program's bitness?
- If not, how are they defined?
- Is it something to do with the compiler used for the host program?
- Will pointer length vary between Excel or Word or SolidWorks hosts?