Modifying CString Contents Directly
In most situations, you should use CString member functions to modify the contents of a CString object or to convert the CString to a C-style character string.
However, there are certain situations, such as working with operating-system functions that require a character buffer, where it is advantageous to directly modify the CString contents.
The GetBuffer and ReleaseBuffer member functions allow you to gain access to the internal character buffer of a CString object and modify it directly. The following steps show how to use these functions for this purpose:
-
Call GetBuffer for a CString object and specify the length of the buffer you require.
-
Use the pointer returned by GetBuffer to write characters directly into the CString object.
-
Call ReleaseBuffer for the CString object to update all the internal CString state information, such as the length of the string. After modifying a CString object's contents directly, you must call ReleaseBuffer before calling any other CString member functions.
CString 型转化成 BSTR 型
当我们使用 ActiveX 控件编程时,经常需要用到将某个值表示成 BSTR 类型.BSTR 是一种记数字符串,Intel平台上的宽字符串(Unicode),并且可以包含嵌入的 NULL 字符。
可以调用 CString 对象的 AllocSysString 方法将 CString 转化成 BSTR:
CString str;
str = .....; // whatever
BSTR bStr = str.AllocSysString();
BSTR型转换为CString
如果你在 UNICODE 模式下编译代码,你可以简单地写成:
CString convert(BSTR bStr)
{
if(bStr == NULL)
return CString(_T(""));
CString s(bStr); // in UNICODE mode
return s;
}
如果是 ANSI 模式
CString convert(BSTR b)
{
CString s;
if(b == NULL)
return s; // empty for NULL BSTR
#ifdef UNICODE
s = b;
#else
LPSTR p = s.GetBuffer(SysStringLen(b) + 1);
::WideCharToMultiByte(CP_ACP, // ANSI Code Page
0, // no flags
b, // source widechar string
-1, // assume NUL-terminated
p, // target buffer
SysStringLen(b)+1, // target buffer length
NULL, // use system default char
NULL); // don''t care if default used
s.ReleaseBuffer();
#endif
return s;
}