开发者

string to PCWSTR -> strange return(C++)

开发者 https://www.devze.com 2022-12-21 12:03 出处:网络
i\'m really new to C++-programming and i\'ve got an a problem with writing into a xml document. I\'m using a slightly changed example ofxml outputter from msdn (http://msdn.microsoft.com/en-us/librar

i'm really new to C++-programming and i've got an a problem with writing into a xml document.

I'm using a slightly changed example of xml outputter from msdn (http://msdn.microsoft.com/en-us/library/ms766497(VS.85).aspx).

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
}

I'm giving a string to CreateAndAddTestMethodNode which convert it with stringtopcwstr to a pcwstr, or should do it.

//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开发者_StackOverflow result(buf); 
delete[] buf;
PCWSTR pResult = result.c_str(); 
return pResult;
}

But it only returns something like "0x00bb9908 "ﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮﻮ" which causes an access violation in one of the next methods. It would be really great if someone could give me clue where i did the failure.

Thank You.


The result of c_str() gets destroyed along with the result string (when it goes out of scope). You will need to explicitly allocate memory for it.


You could make the return type for stringToPCWSTR as a const reference to PCWSTR i.e. const PCWSTR&

0

精彩评论

暂无评论...
验证码 换一张
取 消