String Parameters

There are several different data types used to represent strings in C/C++. One of the most common is the LPWSTR data type, which is a pointer to the memory location where the string begins. Most DLLs require null-terminated strings, which VBA can pass ByVal. Some C-language DLLs might return LPSTR

pointers that can be copied to VBA strings using API functions. Only those APIs that were specifically written for VB (like APlGlD32.dll) actually accept or return VBA strings.

A null-terminated string is one that ends in an ASCII Null character. To form such a string, append an ASCII zero or use the vbNullChar constant. These two lines of code are equivalent:

param = "abc" & Chr$(0) param = "abc" & vbNullChar

A null string, on the other hand, is an empty string, which is formed using a pair of quotes or the vbNullString constant. The following lines of code are equivalent:

param = vbNullString

For example, to find the Windows folder (the one that contains most of the Windows application and initialization files), use the following:

'Declare the function

Private Declare Function GetWindowsDirectory _ Lib "kernel32" Alias "GetWindowsDirectoryA" ( _ ByVal lpBuffer As String, _ ByVal nSize As Long) As Long

Private Const MAXLEN = 255

Public Function WindowsDir() As String Dim strDirectory As String Dim lngSize As Long Dim lngReturn As Long

'Pre-initialize the string strDirectory = Space(MAXLEN) & Chr(0) 'Initialize the string length lngSize = MAXLEN + 1

'Retrieve the length of the string returned by the function lngReturn = GetWindowsDirectory(strDirectory, lngSize)

If lngReturn <> 0 Then

'Return the string containing the Windows directory, 'using lngReturn to specify how long the string is. WindowsDir = left(strDirectory, lngReturn)

Else

WindowsDir = "" End If End Function

The following table shows some of the more common string data types used by APIs.

Data Type

Prefix

Description

LPWSTR

lpsz

32-bit (long) pointer to a C null-terminated wide string. A wide string is typically a double-byte character.

LPSTR

lpsz

32-bit (long) pointer to a C null-terminated string

LPCSTR

lpsz

32-bit (long) pointer to a constant C null-terminated string

LPTSTR

lpsz

32-bit (long) pointer to a C null-terminated string

LPCWSTR

lpsz

32-bit (long) pointer to a constant C null-terminated wide string

Was this article helpful?

0 0

Post a comment