0

I have to convert a BSTR to CHAR* datatype in C. Is there anyway to do this without using VC++ libraries or functions. The code has to be in pure C. I think 'comutil.h' has got functions but they are in C++ I suppose.

Also, about the SysAllocString function, can we use it in C and convert to CHAR*?. Please help.

Thanks, sveerap

sveerap
  • 841
  • 1
  • 9
  • 20

2 Answers2

2

You can go from a char* to a BSTR with SysAllocStringByteLen(). But this is only safe if the char* contains only ASCII characters, no character conversion takes place. This not causing problems would be pretty rare.

Next hop is MultiByteToWideChar(), you typically want to set the CodePage argument to CP_ACP unless you know that the string is encoded another way. That produces a wide string which you can then pass to SysAllocString() to get the BSTR.

The other way around is WideCharToMultiByte(), passing the BSTR directly will work unless it contains embedded 0 chars. The conversion is lossy anyway however, beware the considerable headache this can cause when you work with strings that contain accented characters or anything else that cannot be represented in the code page you use.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks for the response. I used a comutil.h methods available in vc++ and exposed them a C functions in the dll and using them as utilities. It works but am not sure if it is an efficient approach – sveerap Dec 24 '10 at 02:02
0

It depends how you define "VC++ libraries or functions". The BSTR type is pretty much a VC++ type. If however you consider it a "Windows" type then there are BSTR manipulation functions in "Windows" libraries and "Windows" functions that you can use. It all depends on what you are doing, what compiler you are using, and any other technical limitations. It would have been a good idea to describe why you can't use VC++ libraries in the question.

In fact the BSTR type is quite well understood and documented. See here.

It is not beyond the bounds of possibility, should you be disallowed for some reason from using any of the Microsoft BSTR manipulation functions, to write your own BSTR manipulation functions to convert between a BSTR and a char *.

As a cheap and VERY nasty hack, I have before now cast a BSTR to a char * and then copied every alternate character to a buffer or similar. However this does not cope with special characters and is a very very nasty hack. Please do not do it unless you can guarantee that the characters in the BSTR are all standard ASCII characters (or don't care if they are not) and are only doing it as a quick debug hack or something liek that, rather than proper production quality code.

AlastairG
  • 4,119
  • 5
  • 26
  • 41
  • Thanks for the response. I am visual studio 2008 but have to compile it as pure c code as this code has to be built into a dll which will integrated with a legacy system that can talk to c module only – sveerap Dec 22 '10 at 13:38