tags:

views:

77

answers:

3

I see how to do this using MFC, but what is the best way to convert a LPSTR to a BSTR in C++ using only the win32 libraries.

+3  A: 
#include <comutil.h>

LPSTR myLpstr = "Hello World!";
_bstr_t bstr = _bstr_T(myLpstr);

It also needs library comsupp.lib

James Curran
He said "only the win32 libraries".
JSBangs
"comsupp.lib" is for "COM support". COM is part of Win32.
James Curran
Agreed, but you should probably be using comsuppw.lib (which uses wchar_t* instead of unsigned short* in APIs). It's actually not a Win32 library (not in PSDK, no matching DLL) but a Visual C++ static library. So, you don't need to distribute MFC, but it's still not portable to MingW
MSalters
+2  A: 

Use SysAllocString.

Note that SysAllocString takes an OLECHAR* argument, which is effectively a WCHAR*, not a CHAR*. This shouldn't be a problem unless you're compiling without UNICODE defined--but don't do that.

JSBangs
Whether or not UNICODE is defined is not going to have any effect on an LPSTR. You need to show how to convert the string.
Hans Passant
-1, agree with Hans Passant here. The Unicode define affects `LPTSTR`, not `LPWSTR` or `LPSTR`. Hence this answer is missing the hard part.
MSalters
A: 

Don't know the concrete solution but I think this is gonna help you (especially part II):

The Complete Guide to C++ Strings, Part I - Win32 Character Encodings

The Complete Guide to C++ Strings, Part II - String Wrapper Classes

Regards,

Inno

Inno