我是 C++ 编程的新手,我在写入 xml 文档时遇到了问题。
我使用的是来自 msdn ( http://msdn.microsoft.com/en-us/library/ms766497(VS.85).aspx ) 的 xml 输出器的一个稍微改变的例子。
HRESULT CreateAndAddTestMethodNode(string name)
{
HRESULT hr = S_OK;
IXMLDOMElement* pElement = NULL;
CHK_HR(CreateAndAddElementNode(pXMLDom, L"method", L"\n\t", pClass, &pMethod));
CHK_HR(CreateAndAddAttributeNode(pXMLDom, L"name", stringToPCWSTR(name), pMethod));
//more Attribute Nodes (deleted for better overview ;) )
CleanUp:
SAFE_RELEASE(pMethod);
return hr
}
我给 CreateAndAddTestMethodNode 一个字符串,它用 stringtopcwstr 将它转换为 pcwstr,或者应该这样做。
//convert string to pcwstr
PCWSTR stringToPCWSTR (const std::string& str)
{
int len;
int slength = (int)str.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, buf, len);
std::wstring result(buf);
delete[] buf;
PCWSTR pResult = result.c_str();
return pResult;
}
但它只返回类似 “0x00BB9908” ﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮ”,在下一个方法之一中引起访问违规。 如果有人能告诉我我失败的地方,那就太好了。
谢谢。
最佳答案
c_str()
的结果与 result
字符串一起被销毁(当它超出范围时)。您将需要为其显式分配内存。
关于c++ - 字符串到 PCWSTR -> 奇怪的返回(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2361523/