【发布时间】:2016-07-28 15:19:24
【问题描述】:
关于这个问题有很多问题,我一直在尝试各种解决方案。似乎有几十种方法可以做到这一点,但它们都没有奏效。我对 C++ 和 VS 非常陌生,工作了大约一个月,我正在尝试使用 VC++ 编写一个自动 Excel 程序。我一直试图连接 wchar_t * 和 unsigned long long。我假设第一步是将 unsigned long long “转换”为 wchar_t *。我很抱歉抛出了整个代码,但我认为这可能有助于显示我的目标以及代码中是否存在任何其他弱点。
wchar_t * ex(wchar_t * dest, unsigned long long num);
int main()
{
unsigned long long num = 10;
wchar_t *dest= L"A2:B";
wchar_t * Path=ex(dest, num);
VARIANT param;
param.vt = VT_BSTR;
// param.bstrVal = SysAllocString(L"A2:B10");
param.bstrVal = SysAllocString(Path);
getchar();
return 0;
}
wchar_t * ex(wchar_t * dest, unsigned long long num)
{
// Convert num to wchar_t *
wchar_t *rangeMax = (wchar_t *)num;
// I think this is used to eliminate extra space in other solutions
// but not here. It could be useful.
const int MAX_CHARS = 50;
size_t count = wcsnlen_s(dest, MAX_CHARS);
wprintf(L"The length of the string is %ld characters\n", count);
// Throw dest into buf
wchar_t buf[25] = { 0 };
int r = wcscpy_s(buf, 25, dest);
if (r != 0) {
wprintf(L"wcscpy_s() failed %ld", r);
}
r = wcscat_s(buf, 25, rangeMax);
if (r != 0) {
wprintf(L"wcscat_s() failed %ld", r);
}
wprintf_s(buf);
return buf;
}
ex 是来自 zetcode 的编辑示例。我认为它接近于解决方案,但是当结合 buf 和 rangeMax 时,代码会抛出各种内存异常并失败。
如您所见,连接的 wchar_t * 的最终目的地是通过 SysAllocString 作为 VARIANT 中的 BSTR。
感谢任何有关代码改进以及如何使代码实际运行的建议!
【问题讨论】:
-
您可以在
unsingned long long上使用std::to_wstring 来获取std::wstring。然后您可以从该字符串中获取wchar_t*或使用std::wstring(更简单)。 -
这段代码有几个错误。返回指向局部变量的指针的函数。泄漏内存的函数。类型转换错误。这整件事需要重写。
-
感谢您的帮助!我最终组合 wstrings 并组合它们,然后
wchar_t *string2 = (WCHAR *)string.c_str(); -
该代码是未定义行为的前兆。你为什么抛弃你的
const限定词?有什么特别的原因,还是只是在犹豫买书看书?
标签: c++ windows winapi visual-c++ visual-studio-2015