• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 194
  • Last Modified:

Understanding problem

Hi all

I am having a small problem. I have written a piece of code and want to find what exactly it will react as.

The code is as follows.
BSTR      bstr ;
CString str="hello this is a test" ;
bstr = str.AllocSysString() ;

I wanted to show a message box or u can say wanted to extract the data in the BSTR variable without using a _bstr_t or CString avriable.
So i tried this stunt i.e AfxMessageBox((LPCTSTR)(_bstr_t)bstr);
Please tell me if this will work only as a typecast operator , or it will allocate memory for the BSTR to _bstr_t conversion.

Thanks a lot.
1 Solution
#include "afxpriv.h"

BOOL CAboutDlg::OnInitDialog()
      // TODO: Add extra initialization here

      CString str1("Test Conversion");
      BSTR bstr = T2OLE(str1);

      return TRUE;  // return TRUE unless you set the focus to a control
                    // EXCEPTION: OCX Property Pages should return FALSE
_bstr_t is an object, not a native type, so you are actually calling the _bstr_t constructor, which will indeed allocate memory for the _bstr_t object. Space will also be allocated to store the string itself.

Hope this helps

BSTR is a WCHAR String

AfxMessageBox is a 2 version (by param) function

if you create a none unicode version space must be allocated for the conversion to ASCII

in a unicodeversion you can just write

in a ansi/asciiversion you can use
or other ...W API calls w/o ascii conversion (allocation)
Your question is somwhat unclear.  It seems that you just want to "look at" the text that is in a BSTR.   If so, just place a breakpoint in the code, and then place the mouse over the variable named bstr  -- the current value will appear in a little toottip-like box.

Some background:  
BSTR is just a pointer data type like char* and the compiler/debugger knows how to display them.

Sometimes (even often) you will need to convert to and from a BSTR to a char* -- and that will involve some process that looks at each character in the one array and converting it to the desired type in the other array.

The simplest way to get that conversion done is to use the _bstr_t class object, as you have already done.  _bstr_t is kind of an interesting object:  It actually maintains two copies of the text, one in Wide UNICODE form and one in 8-bit char form.  It provides conversion operators that let you examine the text in either form.

If that does not help, then please supply some more information about what you are trying to accomplish or what else you need to know.

-- Dan

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now