>>one can pass the variable by reference to pass the pointer...
Strings are
never passed by reference to API functions. The reason is strings variables are itself pointers to data and if you pass a pointer to string, you actually pass a pointer-to-pointer to a string which leads to unexpected results (mostly crashes) when done with API.
I learned this lesson a long time ago when I was trying to write a registry access ActiveX component for Visual Basic and repeatedly crashing my VBIDE. The reason was same. The string was supposed to be filled by the calling API function and I was passing it by reference. I was not aware of this fact at that time and kept knocking my head for a long time.
In VB, the (variable-length) string is a 32-bit variable which
points to the location or
contains the address of actual string data. When dealing with APIs, we are not interested with the
location of this variable but the
contents of this variable which is the address of the actual string data (located somewhere else).
If the string is passed by reference of if we pass the value returned by VarPtr function, the location of the string variable is passed to the function which is useless. On the other hand, if the string is passed by value or if we pass the value returned by StrPtr, the contents of this string variable are passed which is the right thing needed by the API function.
Note that the StrPtr function which returns the "contents" or the "address value" stored in a string variable can also be found using the VarPtr function. See the code below.
___
[tt]
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
Private Sub Form_Load()
Dim S As String, L As Long
S = "initialize the string."
'get a pointer to string
'using simple StrPtr function.
Debug.Print StrPtr(S)
'get a pointer to string using VarPtr function.
'copy four bytes from the location of S to L.
CopyMemory L, ByVal VarPtr(S), 4
Debug.Print L
Unload Me
End Sub[/tt]
___
Last but not least is an excellent and comprehensive article from MSDN which explains the storage and management of strings in VB and the way VB interacts with Windows API when passing string data.