SORU
18 Ocak 2009, Pazar


Nasıl FormatMessage kullanmalıyım() doğru C ?

Olmadan:

  • MFC
  • ATL

Nasıl FormatMessage() HRESULT bir hata metni almak için kullanabilir miyim?

 HRESULT hresult = application.CreateInstance("Excel.Application");

 if (FAILED(hresult))
 {
     // what should i put here to obtain a human-readable
     // description of the error?
     exit (hresult);
 }

CEVAP
18 Ocak 2009, Pazar


Burada bir hata iletisi Sistem Geri HRESULT (Bu durumda hresult adlı ya GetLastError() ile değiştirebilirsiniz) almak için doğru yolu:

LPTSTR errorText = NULL;

FormatMessage(
   // use system message tables to retrieve error text
   FORMAT_MESSAGE_FROM_SYSTEM
   // allocate buffer on local heap for error text
   |FORMAT_MESSAGE_ALLOCATE_BUFFER
   // Important! will fail otherwise, since we're not 
   // (and CANNOT) pass insertion parameters
   |FORMAT_MESSAGE_IGNORE_INSERTS,  
   NULL,    // unused with FORMAT_MESSAGE_FROM_SYSTEM
   hresult,
   MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
   (LPTSTR)&errorText,  // output 
   0, // minimum size for output buffer
   NULL);   // arguments - see note 

if ( NULL != errorText )
{
   // ... do something with the string `errorText` - log it, display it to the user, etc.

   // release memory allocated by FormatMessage()
   LocalFree(errorText);
   errorText = NULL;
}

Bu ve David Hanak cevabı arasındaki temel fark FORMAT_MESSAGE_IGNORE_INSERTS bayrak kullanılır. Web sistem beklediğini bilmenin bir yolu yok gibi bir sistem mesajı alırken biraz eklemeler kullanılması gerektiği hakkında belirsiz, ama Raymond Chen notes that you should never use them.

Eğer Visual C kullanıyorsanız FWIW, hayatınızı biraz daha kolay _com_error sınıfını kullanarak yapabilirsiniz:

{
   _com_error error(hresult);
   LPCTSTR errorText = error.ErrorMessage();

   // do something with the error...

   //automatic cleanup when error goes out of scope
}

Ya da doğrudan MFC, ATL ayrılmaz bir parçası olarak farkındayım.

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • CNET

    CNET

    5 Mayıs 2006
  • LardTardProductions's channel

    LardTardProd

    10 NİSAN 2009
  • Ryan Ha

    Ryan Ha

    9 NİSAN 2006