views:

299

answers:

2

Hello, 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 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.

+3  A: 

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.

Lukáš Lalinský
Ahh, shame on me -.-Such a basic thing...Thank you very much for your help ;)
Tronje182
You could also just return the wstring itself from stringToPCWSTR - and call .c_str() on the return value of the function. That'll save you fiddling with memory allocation.
AshleysBrain
That's exactly the way I solved the problem. But thank you for the tip nevertheless.
Tronje182
A: 

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

Vino
How would it help him?
sharptooth