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

Converting variables...

How do I copy a BSTR variable to a char variable?

How do I copy a char variable (of array type) to a BSTR variable?
1 Solution
What's a BSTR?
loyaliserAuthor Commented:
BSTR is a COM variable type. I am building a COM in Visual C++ 6.0 and one of my functions accepts a parameter of type BSTR. I need to convert the BSTR variable to a char so that I can pass it to a function that accepts a char parameter.

That's it... make any sense? Thanks...
loyaliserAuthor Commented:
As far as I know BSTR is similar to the String data type, however, I don't know if it shares the same API methods.
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

the class _bstr_t defined in <comdef.h> automates the conversion from and to BSTR or char*.

intern the following functions are used:

 BSTR _com_util::ConvertStringToBSTR(const char* pSrc)

 char* _com_util::ConvertBSTRToString(BSTR pSrc)


There are several ways to perform this action.  One I frequently use is snprintf, which can do the job like this:
  const int
    max= 255;

  _snprintf( buffer, max, "%S", your_bstr_here );

Notice that the "%S" is a capital S.

Although this method works, the preferred method is to use the WideCharToMultiByte function.

Another preferred method works in the context of ATL and uses the USES_CONVERSION and W2A macros.

To do the inverse of these operations, use the MultiByteToWideChar, SysAllocString, USES_CONVERSION and A2W functions and macros.

loyaliserAuthor Commented:
Yeah... I need the method that works in the ATL, because the code is within an ATL COM object.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

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