Page 1 of 1

[MFC] Cum pasez CString unei functii Windows API?

Posted: 11 Feb 2012, 11:27
by Ovidiu Cucu
Intrebare
Multe functii Windows API cer ca parametru LPCTSTR sau LPTSTR.
Cum pasez un tip CString acestor functii?

Raspuns
  • Daca se cere LPCTSTR, putem utiliza CString::GetString sau CString::opertor LPCTSTR.
  • Daca se cere LPTSTR, putem apela CString::GetBuffer sau CString::GetBufferSetLength.
Exemple
  1. Code: Select all

       // GlobalAddAtom gets LPCTSTR
       CString strAtom = _T("demo atom text");
       // ...
       ATOM atom = ::GlobalAddAtom(strAtom.GetString());
    
  2. Code: Select all

       // RegisterWindowMessage gets LPCTSTR
       CString strMsg = _T("demo message text");
       // ...
       UINT uMsg = ::RegisterWindowMessage((LPCTSTR)strMsg);
    
  3. Code: Select all

       // CreateDirectory gets LPCTSTR
       CString strDir = _T("demo directory"); 
       // ...
       BOOL bRet = ::CreateDirectory(strDir, NULL);
       // Note: implicit (LPCTSTR) cast has been performed.
    
  4. Code: Select all

       // GetCurrentDirectory gets LPTSTR
       CString strCurDir;
       ::GetCurrentDirectory(MAX_PATH, strCurDir.GetBuffer(MAX_PATH));
       strCurDir.ReleaseBuffer();
    
Note
  • Important: O greseala frecvent intalnita este de a face dublu cast (LPTSTR)(LPCTSTR):

    Code: Select all

       // GetSystemDirectory gets LPTSTR
       CString strSysDir;
       ::GetSystemDirectory((LPTSTR)(LPCTSTR)strSysDir, MAX_PATH);
       // ...
       // Bang!!! The program can crash, sooner or later.
  • CString::GetString nu exista in MFC6.0 sau mai vechi. Utilizati operatorul LPCTSTR care in fond face acelasi lucru.
  • In versiunile noi de MFC, CString este implementat ca teplate, in consecinta puteti gasi documentatia la CStringT si CSimpleStringT. De asemenea puteti gasi operatorul PCXSTR in loc de LPCTSTR. In orice caz, putem in continuare folosi "sintaxa veche" din exemplele date mai sus.
Resurse [MSDN]
<< Back to MFC index

[MFC] Cum pasez CString unei functii Windows API? [2]

Posted: 05 Dec 2013, 15:28
by Ovidiu Cucu
In loc de CString::GetBuffer sau CString::GetBufferSetLength plus CString::ReleaseBuffer, se poate folosi clasa comuna MFC/ATL CStrBuf.
Exemplul #4 de mai sus, se poate asfel rescrie mai compact, astfel:

Code: Select all

    CString strCurDir;
    ::GetCurrentDirectory(MAX_PATH, CStrBuf(strCurDir, MAX_PATH));
Resurse [MSDN]