How to Call lstrcpy to Receive LPSTR Returned from Other APIs

ID: Q78304


The information in this article applies to:


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 by receiving the return value as a long integer data type. Then use the lstrcpy Windows API function to copy the returned string into a Visual Basic string.


MORE INFORMATION

This information is included with the Help file provided with Microsoft Professional Toolkit for Visual Basic version 1.0, Microsoft Visual Basic version 2.0, and Microsoft Visual Basic version 3.0.

An LPSTR Windows API data type is actually a far pointer to a null-terminated string of characters. Because 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 (UAE) or general protection (GP) fault when you call lstrcpy.

The following is an example program that demonstrates how to use lstrcpy to retrieve an LPSTR pointer returned from the Windows API GetDOSEnvironment routine.

NOTE: The capability of the Windows API GetDOSEnvironment routine is already available through the Environ function built into Visual Basic. Therefore, so the program is useful only to demonstrate how to use lstrcpy.


'*** General declarations ***

Declare Function GetDosEnvironment Lib "Kernel" () As Long

' Enter the following Declare statement as one, single 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$ = Trim$(DOSEnv$)
   DOSEnv$ = Left$(DOSEnv$, Len(DOSEnv$) - 1)
   Form1.Print DOSEnv$
End Sub 

Additional query words: 2.00 3.00


Keywords          : 
Version           : 
Platform          : 
Issue type        : 

Last Reviewed: June 17, 1999