String Manipulation Functions

Windows CE .NET

To handle strings that are allocated by one component and freed by another, Automation defines a special set of functions. These functions use the following data type.

typedef OLECHAR * BSTR;

These strings are zero-terminated and in most cases they can be treated like OLECHAR* strings. However, you can query a BSTR for its length rather than scan it, therefore it can contain embedded null characters. The length is stored as a 32-bit integer at the memory location preceding the data in the string. Instead of reading this location directly, applications should use the string manipulation functions to access the length of a BSTR.

In 32-bit OLE, BSTRs use Unicode like all other strings in 32-bit OLE. In 16-bit OLE, BSTRs use ANSI. Win32 provides the MultiByteToWideChar and WideCharToMultiByte functions to convert ANSI strings to Unicode and Unicode strings to ANSI.

In situations where a BSTR will not be translated from ANSI to Unicode, or vice versa, you can use BSTRs to pass binary data. However, the preferred method of passing binary data is to use a SAFEARRAY of VT_UI1.

Automation may cache the space allocated for BSTRs. This speeds up the SysAllocString/SysFreeString sequence. However, this may also cause the IMallocSpy interface to assign leaks to the wrong memory user because it is not aware of the caching done by Automation.

For example, if the application allocates a BSTR and frees it, the free block of memory is put into the BSTR cache by Automation. If the application then allocates another BSTR, it can get the free block from the cache. If the second BSTR allocation is not freed, IMallocSpy will attribute the leak to the first allocation of the BSTR.

A null pointer is a valid value for a BSTR variable. By convention, it is always treated the same as a pointer to a BSTR that contains zero characters. Also by convention, calls to functions that take a BSTR reference parameter must pass either a null pointer or a pointer to an allocated BSTR. If the implementation of a function that takes a BSTR reference parameter assigns a new BSTR to the parameter, it must free the previously referenced BSTR.

The following table shows the string manipulation functions.

String manipulation function Description
SysAllocString Creates and initializes a string.
SysAllocStringByteLen Creates a zero-terminated string of a specified length (32-bit only).
SysAllocStringLen Creates a string of a specified length.
SysFreeString Frees a previously created string.
SysReAllocString Changes the size and value of a string.
SysReAllocStringLen Changes the size of an existing string.
SysStringByteLen Returns the length of a string in bytes (32-bit only).
SysStringLen Returns the length of a string.

Last updated on Wednesday, April 13, 2005

© 2005 Microsoft Corporation. All rights reserved.

Show: