문제

I have two projects, A and B

Project A is compiled with:
1. Standard Windows Libraries
2. Multi-byte character set
3. NO common language support

Project B is compiled with:
1. MFC as a dynamic dll
2. Multi-byte character set
3. WITH using common language support

The following function is defined in project A:

LPCTSTR CAppProxy::DriverName(IDriverAgent *driver)  
{  
  BSTR bstr;  
  HRESULT hr = driver->get_Name(&bstr);  
  CString str = CString(bstr);  
  return(str);  

}

and is called from project B using:

CString name = appProxy->DriverName(driver);

but when driver name is called, the contents of "name" are garbage

도움이 되었습니까?

해결책

A classic mistake, you're returning a pointer to a local object which reaches the end of its lifetime at the end of the function. The stack containing the string is released and overwriten with random stuff.

More specifically, you're returning a pointer to a data structure inside the CString object which is invalidated when the CString is destroyed.

If both projects are using the same version of CString you could return one of those instead of LPCTSTR.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top