1

I have a question how can BSTR accepts a number the second line here gives an error

    unsigned int number =10;
    BSTR mybstr=SysAllocString(number);

also this line gives an error

VarBstrCat(mybstr, number, &mybstr);

Thank you :) your help will be greatly appreciated :)

Rehab Reda
  • 193
  • 7
  • 16
  • 1
    Well, what does the error say? Also, see the documentation for *what* the argument accepted is really used for: [`SysAllocString(number)`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms221458(v=vs.85).aspx) is most definitely *wrong* and should have raised a warning or two. – user2864740 Sep 11 '14 at 22:53
  • here is the error cannot convert parameter 1 from 'std::wstring' to 'const OLECHAR *' – Rehab Reda Sep 11 '14 at 22:56
  • `SysAllocString` does not have an overload taking an int. – MicroVirus Sep 11 '14 at 22:58
  • Thank you MicroVirus so much :) but if I have integer and I need it to be converted to BSTR how can i do this ? – Rehab Reda Sep 11 '14 at 23:04

2 Answers2

3

First, SysAllocString accepts const OLECHAR*, not int

Second, VarBstrCat's second parameter is BSTR, not again int

To convert int to BSTR, you can do for example like this:

std::wstring s = std::to_wstring(number); // needs C++11
BSTR mybstr = SysAllocString(s.c_str());

UPDATE: Or a bit more efficient, as suggested by Remy Lebeau in comments:

BSTR mybstr = SysAllocStringLen(s.c_str(), s.length());

UPDATE2: If your compiler doesn't support C++11, you can use C function swprintf():

wchar_t buf[20];
int len = swprintf(buf, 20, L"%d", number);
BSTR mybstr = SysAllocStringLen(buf, len);
Community
  • 1
  • 1
Anton Savin
  • 40,838
  • 8
  • 54
  • 90
1

You need to convert the number to a unicode string before you can get a BSTR of it. For this you can use _itow which converts an int into a unicode string.

unsigned int number = 10;
wchar_t temp_str[11]; // we assume that the maximal string length can be 10
_itow(number, temp_str, 10);
BSTR mybstr = SysAllocString(temp_str);
Adam
  • 851
  • 6
  • 10