Lstrcpy API Call to Receive LPSTR Returned from Other APIs

ID Number: Q78304

1.00

WINDOWS

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.

This information applies to the Microsoft Visual Basic programming

system version 1.0 for Windows.

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 routine lstrcpy 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" message when you call lstrcpy.

The following is a program example that demonstrates using lstrcpy to

retrieve a LPSTR returned from the Windows API routine

GetDOSEnvironment. Note that the capability of the Windows API routine

GetDOSEnvironment is already available through the Environ function

built into Visual Basic; thus, the following program mainly serves as

an example of using lstrcpy.

'*** Global Module declarations ***

Declare Function GetDosEnvironment Lib "Kernel" () As Long

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$(Left$(DOSEnv$, Len(DOSEnv$) - 1))

Form1.Print DOSEnv$

End Sub

Additional reference words: 1.00