Converting Unicode and ANSI Strings

[This is preliminary documentation and subject to change.]

Active Accessibility uses Unicode strings, as defined by the BSTR data type. If your application does not use Unicode strings, or if you want to convert strings for certain API calls, use the MultiByteToWideChar and WideCharToMultiByte Win32 functions to perform necessary conversion. You can use WideCharToMultiByte to convert a Unicode string to an ANSI string; the MultiByteToWideChar function does the opposite. The Babble sample application uses the WideCharToMultiByte function in several places to perform Unicode to ANSI string conversion. The following application-defined function, from the Babble sources, illustrates how to properly call the function.

DWORD GetObjectName(LPOBJINFO poiObj,LPSTR lpszBuf, int cchBuf)
{
    DWORD dwRetVal;
    BSTR  bszName;
    IAccessible* pIAcc;
    long* pl;

    bszName = NULL;

    // Get the object out of the structure.
    pl = poiObj->plObj;

    pIAcc =(IAccessible*)pl;

    // Get the object's name.
    pIAcc->get_accName(poiObj->varChild, &bszName);
    
    // Did we get name string?
    if (bszName)
    {
        // Convert the string Unicode to ANSI.
        if (WideCharToMultiByte(CP_ACP, 0, 
                            bszName,
                            WC_SEPCHARS, // -1
                            lpszBuf,
                            cchBuf,
                            NULL, NULL))
        {
            SysFreeString(bszName);

            dwRetVal = NO_ERROR;
        }
        else
        {
            dwRetVal = GetLastError();
        }

        return(dwRetVal);
    }
        
    
    // Need general failure handling routine
    MessageBeep(MB_ICONEXCLAMATION);
    
    return(ERROR_INVALID_FUNCTION);
}
 

For more information about these string conversion functions, see their references in the Platform SDK.