【问题标题】:How to Convert int to BSTR?如何将 int 转换为 BSTR?
【发布时间】:2014-09-11 22:52:08
【问题描述】:

我有一个问题 BSTR 如何接受数字 这里的第二行给出了一个错误

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

这一行也报错

VarBstrCat(mybstr, number, &mybstr);

谢谢 :) 您的帮助将不胜感激 :)

【问题讨论】:

  • 那么,错误说明了什么?另外,请参阅文档,了解所接受的参数真正用于什么SysAllocString(number) 绝对是错误,应该发出一两个警告。
  • 这里是错误 cannot convert parameter 1 from 'std::wstring' to 'const OLECHAR *'
  • SysAllocString 没有采用 int 的重载。
  • 非常感谢 MicroVirus :) 但是如果我有整数并且需要将其转换为 BSTR,我该怎么做?

标签: c++ bstr


【解决方案1】:

首先,SysAllocString accepts const OLECHAR*, not int

第二,VarBstrCat's second parameter is BSTR, not again int

要将int 转换为BSTR,您可以这样做:

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

更新:或者更高效一点,正如 cmets 中 Remy Lebeau 所建议的那样:

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

UPDATE2:如果你的编译器不支持C++11,你可以使用C函数swprintf()

wchar_t buf[20];
int len = swprintf(buf, 20, L"%d", number);
BSTR mybstr = SysAllocStringLen(buf, len);

【讨论】:

  • 谢谢 Anton :) 但是你能给我一个建议如何将 int 转换为 BSTR 吗? :)
  • 由于wstring 知道自己的长度,我建议使用SysAllocStringLen() 代替:BSTR mybstr = SysAllocStringLen(s.c_str(), s.length());
  • 谢谢 Anton,但它似乎不适用于我 错误 'to_wstring' : is not a member of 'std'
  • @RehabReda 这是一个 C++11 函数,要么通过 -std=c++11 启用它,要么使用例如 swprintf
【解决方案2】:

您需要将数字转换为 unicode 字符串,然后才能获得它的 BSTR。 为此,您可以使用 _itowint 转换为 unicode 字符串。

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);

【讨论】:

    猜你喜欢
    • 2010-09-15
    • 2010-10-11
    • 1970-01-01
    • 2016-02-14
    • 2015-09-27
    • 2018-01-11
    • 2011-04-08
    • 2013-05-12
    • 1970-01-01
    相关资源
    最近更新 更多