Re: Converting BSTR to char*

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Aidal wrote:

Hi NG.

First of, I'm new to VC++ and C++ in general, so don't bite my head of for asking noob questions please :)

I'm trying to build a rather simple DLL and I need to convert a BSTR to char*.


First, you should realize that a BSTR is a (special kind of) wide character string (16-bit), whereas char* is a narrow (8-bit) string.

Second, you may not really be wanting a char*. If you are in a Unicode build (a wise choice, usually) then you probably want a wchar_t*. Learn to use TCHAR, LPTSTR, etc, which are narrow in ANSI builds and wide in UNICODE builds.

Third, you probably really want a const char* (or const wchar_t*).

Fourth, use of BSTR is much easier if you use the _bstr_t wrapper. This actually maintains both a narrow and wide string internally, and has cast operators for both const char* and const wchar_t*.

C++ string handling in Windows is not easy. Good luck!

David Wilkinson
.



Relevant Pages

  • Re: Newbie
    ... A 'string' to VB is a 'BSTR' to C++, and to pass a string from VB to C++ is ... Once you have a char* in C++, this is a char array so the members of this ...
    (microsoft.public.dotnet.languages.vc)
  • Re: Combo Box String to char*
    ... Well, the real problem is most likely that the function should have been a const char *, ... or better still, an LPCTSTR parameter. ... number of characters in the string; if you give a longer value, ...
    (microsoft.public.vc.mfc)
  • Re: case insentisive file search
    ... CopyStringPrefix(const char *String, size_t PrefixLength) ... FileName = CopyString; ...
    (comp.lang.c)
  • Re: String Comparision
    ... int comp(const char *s, const char *t) { ... int comp(const restrict char *s, const char *t) { ... It could be argued that a lack of a string is less than an empty string, and that if both elements are "lack of string" they are of the same value. ...
    (comp.lang.c)
  • Re: mallocs, stuctures and objects ... oh my ...
    ... > CString to a BSTR and be done with it. ... Just about anything would be faster than a CString. ... std::string or a char[] if you know that the ... BSTR is a UNICODE string with an extra 4 bytes before the ...
    (microsoft.public.vc.mfc)