-3

I want to convert a char array, e.g. char myArray[size] to a _bstr_t string. I tried this, but it doesn't work:

_bstr_t test;

for (int i = 0; i < myArrayLength; i++) {
    test = test + (_bstr_t) myArray[i];
}
hichris123
  • 10,145
  • 15
  • 56
  • 70
niko85
  • 303
  • 2
  • 12
  • Voting to re-open, since the presumed duplicate is tagged [tag:c]. And since `_bstr_t` is a C++ class, that answer doesn't apply (even if parts of it could be re-used/re-worked to match). – IInspectable Jun 27 '16 at 13:48
  • 2
    @IInspectable I disagree. There is [this](http://stackoverflow.com/a/606089/4342498) answer which shows how to do it in C++ which answers this question. – NathanOliver Jun 27 '16 at 13:56
  • @NathanOliver: That's not the model that SO is looking for: Close a question as a duplicate of another question (asking for a different programming language), and sift through the answers to find the one that doesn't address the question asked, because it, too, uses a programming language that doesn't match the question. Instead, re-open this question, and have an answer here, that addresses the question asked. – IInspectable Jun 27 '16 at 14:00
  • @IInspectable tell that to the users writing Swift answers on Objective-C questions. – JAL Jun 27 '16 at 17:10

1 Answers1

0

The _bstr_t class provides a conversion c'tor (_bstr_t::_bstr_t) that takes a const char*. It performs character conversion from ANSI code page encoding (using the thread's current locale) to UTF-16, and constructs a _bstr_t object:

 _bstr_t bstr = _bstr_t(myArray);

Note, that there is also a binary _bstr_t::operator+(), that takes a const char* as its left-hand side. The following is also allowed:

_bstr_t test;
...
_bstr_t bstr = myArray + test;


In case your input char array uses an encoding other than ASCII or ANSI using the current code page, you will have to manually convert from the source encoding to UTF-16 using MultiByteToWideChar, and construct a _bstr_t from the wchar_t array.
IInspectable
  • 46,945
  • 8
  • 85
  • 181