LSTRCPY API Call to Receive LPSTR Returned From Other APIs
See Also
This article is reprinted from the Microsoft Knowledge Base. To view the article, maximize your help window. This information applies to Visual Basic for Windows, versions 2.0 and 3.0.
Summary:
Because Microsoft Visual Basic does not support a pointer data type,
you cannot directly receive a pointer (such as a LPSTR) as the return
value from a Windows API or DLL function. You can work around this
limitation by receiving the return value as a long integer data type
and then using the lstrcpy Windows API function to copy the returned
string into a Visual Basic string.
More Information:
An LPSTR Windows API data type is actually a far pointer to a
null-terminated string of characters. Because an LPSTR is a far
pointer, it can be received as a four byte data type, such as a Visual
Basic long integer. Using the Visual Basic "ByVal" keyword, you can
pass the address stored in a Visual Basic long integer back to the
Windows API lstrcpy routine to copy the characters at that address
into a Visual Basic string variable. Because lstrcpy expects the
target string to be long enough to hold the source string, you should
pad any Visual Basic string passed to lstrcpy to have a size large
enough to hold the source string before passing it to lstrcpy. Failure
to allocate enough space in the Visual Basic string may result in an
Unrecoverable Application Error or General Protection Fault when
you call lstrcpy.
The following is an example program that demonstrates the use of
lstrcpy to retrieve a LPSTR pointer returned from the Windows API
GetDOSEnvironment routine. Note that the capability of the Windows
API GetDOSEnvironment routine is already available through the
Environ function built into Visual Basic; therefore, the following
program mainly serves as an example of using lstrcpy.
'*** General declarations ***
Declare Function GetDosEnvironment Lib "Kernel" () As Long
' The following Declare statement must appear on one line.
Declare Function lstrcpy Lib "Kernel" (ByVal lpString1 As Any, ByVal
lpString2 As Any) As Long
'*** Form Click event code ***
Sub Form_Click()
Dim lpStrAddress As Long, DOSEnv$
' Allocate space to copy LPSTR into
DOSEnv$ = Space$(4096)
' Get address of returned LPSTR into a long integer
lpStrAddress = GetDOSEnvironment()
' Copy LPSTR into a Visual Basic string
lpStrAddress = lstrcpy(DOSEnv$, lpStrAddress)
' Parse first entry in environment string and print
DOSEnv$ = RTrim$(LTrim$(DOSEnv$, Len(DOSEnv$) - 1))
Form1.Print DOSEnv$
End Sub