16,472
社区成员
发帖
与我相关
我的任务
分享
CString strText;
TCHAR* pChar = strText.GetBuffer( 50 );
_tcscpy( pChar, _T("GetBuffer test...") );
TRACE( _T("strText:%s; len:%d \n"), strText, strText.GetLength() );
strText.ReleaseBuffer();
TRACE( _T("strText:%s; len:%d \n"), strText, strText.GetLength() );
CString strTmp2;
char *pNum=strTmp2.GetBuffer(m_recData.GetLength()/2); //只是获取一个指针而已
Str2Num(pNum, m_recData.GetBuffer(10), m_recData.GetLength());//对这个指针的内存赋值
m_recData.ReleaseBuffer();//释放
strTmp2.ReleaseBuffer(); // 看下面的实现,你的pNum有没有结尾符?
// 所以你这个问题还是在你的Str2Num这个函数中,
// 如果你的这个函数没有对PNum赋值的话,只是对这个指针指向什么的做修改就会出问题。
// 你要是这样干嘛不new一个char数组出来而用CString呢?
struct CStringData
{
long nRefs; // reference count
int nDataLength; // length of data (including terminator)
int nAllocLength; // length of allocation
// TCHAR data[nAllocLength]
TCHAR* data() // TCHAR* to managed data
{ return (TCHAR*)(this+1); }
};
_AFX_INLINE int CString::GetLength() const
{ return GetData()->nDataLength; }
_AFX_INLINE CStringData* CString::GetData() const
{ ASSERT(m_pchData != NULL); return ((CStringData*)m_pchData)-1; }
LPTSTR CString::GetBuffer(int nMinBufLength)
{
ASSERT(nMinBufLength >= 0);
if (GetData()->nRefs > 1 || nMinBufLength > GetData()->nAllocLength)
{
#ifdef _DEBUG
// give a warning in case locked string becomes unlocked
if (GetData() != _afxDataNil && GetData()->nRefs < 0)
TRACE0("Warning: GetBuffer on locked CString creates unlocked CString!\n");
#endif
// we have to grow the buffer
CStringData* pOldData = GetData();
int nOldLen = GetData()->nDataLength; // AllocBuffer will tromp it
if (nMinBufLength < nOldLen)
nMinBufLength = nOldLen;
AllocBuffer(nMinBufLength);
memcpy(m_pchData, pOldData->data(), (nOldLen+1)*sizeof(TCHAR));
GetData()->nDataLength = nOldLen;
CString::Release(pOldData);
}
ASSERT(GetData()->nRefs <= 1);
// return a pointer to the character storage for this string
ASSERT(m_pchData != NULL);
return m_pchData;
}
void CString::ReleaseBuffer(int nNewLength)
{
CopyBeforeWrite(); // just in case GetBuffer was not called
if (nNewLength == -1)
nNewLength = lstrlen(m_pchData); // zero terminated
ASSERT(nNewLength <= GetData()->nAllocLength);
GetData()->nDataLength = nNewLength;
m_pchData[nNewLength] = '\0';
}
void CString::CopyBeforeWrite()
{
if (GetData()->nRefs > 1)
{
CStringData* pData = GetData();
Release();
AllocBuffer(pData->nDataLength);
memcpy(m_pchData, pData->data(), (pData->nDataLength+1)*sizeof(TCHAR));
}
ASSERT(GetData()->nRefs <= 1);
}