VC++:如何将 CString 转换为 TCHAR*

VC++: how-to convert CString to TCHAR*

VC++:如何将 CString 值转换为 TCHAR*。一种方法是 GetBuffer(..) 函数。有没有其他方法可以将 CString 转换为 TCHAR*。

CString::GetBuffer() 不进行任何转换,它提供对字符串的直接访问。

复制CString

TCHAR* buf = _tcsdup(str);
free(buf);

TCHAR* buf = new TCHAR[str.GetLength() + 1];
_tcscpy_s(buf, str.GetLength() + 1, str);
delete[]buf;

然而上面的代码通常是没有用的。您可能想像这样修改它:

TCHAR buf[300];
_tcscpy_s(buf, TEXT("text"));

通常你需要这样做来将数据读入缓冲区,所以你想使缓冲区大小大于当前大小。

或者您可以只使用 CString::GetBuffer(),同样您可能希望使缓冲区大小更大。

GetWindowText(hwnd, str.GetBuffer(300), 300);
str.ReleaseBuffer(); //release immediately
TRACE(TEXT("%s\n"), str);

在其他情况下你只需要const cast const TCHAR* cstr = str;

最后,TCHAR不是很有用。如果您的代码与 ANSI 和 unicode 兼容,那么您不妨将其设为仅 unicode。但这只是一个建议。

这取决于您需要非常量的原因 TCHAR*。主要有两种情况:

  1. 手动更新一个CString object:

    In that case you will have to call CSimpleStringT::GetBuffer (specifying the minimal length of the final string), update the contents, and call CSimpleStringT::ReleaseBuffer的内容。调用 ReleaseBuffer 是强制性的,因为它会更新内部状态。未能调用 ReleaseBuffer 可能导致字符串暴露意外行为。

  2. 无法在接口上公开常量正确性:

    如果是这种情况,您可以更新接口以采用 const TCHAR* TCHAR*,并通过传递 CString 对象来调用 CSimpleStringT::operator PCXSTR
    如果您无法更新界面,最好将副本复制到 [=16] =] 数组并传递指向此副本的指针。
    如果您可以确保实现永远不会修改通过 TCHAR* 参数引用的内容,则可以使用 const_cast 代替.不建议这样做,因为它可能会在将来通过修改不相关的代码引入错误。