2010-03-02 2 views
1

저는 C++ 프로그래밍에 새로운 것이므로 xml 문서 작성에 문제가 있습니다.string to PCWSTR -> 이상한 반환 (C++)

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 
} 

은 내가 PCWSTR에 stringtopcwstr로 변환, 또는 그것을해야 CreateAndAddTestMethodNode에 문자열을주고있다. 내가 실패를 한 경우 누군가가 나에게 단서를 얻을 수 있다면

//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"وووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووووو "뭔가를 반환합니다. 정말 좋은 것입니다.

감사합니다.

답변

3

result 문자열 (범위를 벗어나는 경우)과 함께 c_str()의 결과가 삭제되므로 명시 적으로 메모리를 할당해야합니다.

+0

아, 수치를 PCWSTR하는 const를 기준으로 stringToPCWSTR에 대한 반환 유형을 만들 수 ... 는 당신의 도움을 주셔서 대단히 감사합니다;) – Tronje182

+0

stringToPCWSTR에서 wstring 자체를 반환하고 함수의 반환 값에 대해 .c_str()을 호출 할 수도 있습니다. 그러면 메모리 할당을 줄여 줄 수 있습니다. – AshleysBrain

+0

그게 바로 내가 문제를 해결 한 방법이야. 그럼에도 불구하고 팁을 주셔서 감사합니다. – Tronje182

0

당신은 나를 이러한 기본적인 일을 -.-에 즉 const를 PCWSTR &

+0

어떻게 도움이 될까요? – sharptooth