This article was previously published under Q187675
This article demonstrates how to copy a string to a byte array withoutusing a Unicode conversion. This technique is useful if you need to pass astring to a function that requires Unicode. The article includesinstructions to create a sample project that demonstrates this information.
This article assumes that you know the difference between ANSI and Unicodestrings. Although Visual Basic internally converts strings to Unicode forprocessing, strings are passed to functions as ANSI. Some functions, suchas NetUserGetInfo, only accept Unicode strings. If you pass a string fromVisual Basic to a function that only accepts Unicode strings, the functionwill return incomprehensible data. To pass a string to a function that onlyaccepts Unicode strings, you need to convert the string into a byte array.
To convert a string to a byte array, create a dynamic byte array. Set yourstring variable equal to the byte array. When you loop through theindividual elements of the byte array, you will get the Unicode charactercode for that character
In the case of the English character set, the low-order byte value is thesame as the ANSI character code for that character while the high-orderbyte is a zero.
The next section shows how to create a sample project that demonstratesconverting a string in Visual Basic to a byte array.
Start a new Standard EXE project in Visual Basic. Form1 is created by default.
Copy the following code to the Code window of Form1:
Option Explicit Private Sub Form_Click() Dim strTest As String Dim bytArray() As Byte Dim intcount As Integer strTest = "This is my test string." bytArray = strTest For intcount = 0 To UBound(bytArray) Debug.Print bytArray(intcount); "= " & Chr(bytArray(intcount)) Next End Sub
On the Run menu, click Start or press the F5 key to start the program. Click on the form and see the results in debug window. Because the string variable contains only English characters, each element contains either a Unicode character code corresponding to a English character or a zero.
To then pass the byte array as a Unicode string argument to an API function, pass the first element of the byte array. By default, the first element is 0 unless either the first element is clearly different in the array declaration or Option Base 1 is specified in your module. For an example of passing a byte array to the NetUserGetInfo function, please see the following article in the Microsoft Knowledge Base:
151774 : How To Call NetUserGetInfo API from Visual Basic
For more information about ANSI and Unicode, see Chapter 16 "InternationalIssues" in Part 2 of the Visual Basic Programmer's Guide.