Search code examples
stringvb6user-defined-types

How are fixed vs. variable length stings handled differently in VB6 UDTs?


In VB6, I can use either fixed or variable length strings in a UDT:

Public Type MyRecord
    VariableLengthString As String
    FixedLengthString As String * 80
End Type

I would expect FixedLengthString to allocate 160 bytes in the UDT, and if I had an array of these UDT's, the fixed length string data is inline.

What's going on with VariableLengthString? Is it allocated on the heap?

Therefore, if I do this:

Dim record1 As MyRecord
Dim record2 As MyRecord
record1.VariableLengthString = "a"
record2 = record1

... obviously record2.VariableLengthString will be "a". But, if I do this:

record2.VariableLengthString = "b"

... then what is the value of record1.VariableLengthString?

Update: It turns out that the result is still "a", which means the string is copied. So is it not on the heap?

My test code:

record1.VariableLengthString = "a"
record2 = record1
? record2.VariableLengthString
a
record2.VariableLengthString = "b"
? record1.VariableLengthString
a

Solution

  • Basically "as string" allocates a BSTR in VB6. OLE (the technology underlying VB6) handles BSTRs in special ways including maintaining a cache to make string manipulation faster. This article on String Manipulation in MSDN explains it more detail. The UDT points to a BSTR stucture that is basically a 32bit length field followed by the characters of the string. It is Unicode aware. The space allocated to a BSTR is 4 bytes + the number of bytes to store the characters. So it is variable not fixed like Fixed Length String.