c++ - 字符串到 PCWSTR -> 奇怪的返回(C++)

标签 c++ xml access-violation

我是 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/

相关文章:

c++ - _DebugHeapDelete 终止时访问冲突

c# - 为什么 *(int*)0=0 不会导致访问冲突?

c++ - 为什么两种情况下的行为不同 1st。整数 i = 1,2,3;和第二。诠释我;我 = 1,2,3;

c++ - multimap 与next_permutation C++的结合使用

java - 如何使用 StAX 将元素添加到现有 XML 文件?

c# - MSBuild - XPath - XmlPeek 可以读取但 XmlPoke 不能写入

c++ - 如何使用外部高清摄像机作为 Visual Studio、OpenCV 项目的输入?

c++ - Lua C++ 表迭代

java - 空指针异常,我不知道为什么

c++ - 带余数的动态二维数组访问冲突