Guide to BSTR and C String Conversions

Introduction

One of the confusing aspects of Windows programming is managing the conversion of Visual Basic style strings to/from C language style strings. It isn't that it is so difficult, it is just difficult to remember the details. It is usually not done often, and the MSDN documentation is so voluminous that it is difficult to find answers to your questions. But, the worst part is that you could perform some typecast that compiles fine, but doesn't work the way you expect. This results in code that doesn't work, and the bugs are hard to track down. After some experience, you learn to make sure your string conversions are doing what you expect.

C strings are arrays of characters terminated by a NULL character. Visual Basic strings differ in that the length of the string precede the characters in the string. So, a VB string knows its own length. In addition, all VB strings are Unicode (16 bits per character).

String Types

BSTR/C String conversions are required if:

You are doing COM programming in C/C++

You are writing multiple language applications, such as C++ DLL's accessed by Visual Basic applications.

C Language String Types and Classes

This article deals with the following C/MFC/ATL string types:

String Type

Description

char/wchar/TCHAR

The C strings for ANSI and Unicode

CString

The C++/MFC class wrapper for C strings

BSTR

The Visual Basic string type

_bstr_t

A C++ class wrapper for the Visual Basic string type

CComBSTR

Yet another C++ class wrapper for the Visual Basic string type used predominately in ATL code

Demo Project

The demo project is just an MFC dialog-based application with buttons for each type of conversion. It is built using VC++ 6.0. It uses a couple of support functions you may find helpful: