2014-02-12 145 views
0

我有一個宏,我使用這種方式:宏不執行功能

int GL = 0; 
GL = GetLastError(); 
DEBUG_MESSAGE(ERR, "RegOpenKeyEx failed. Error code = '%u'. Error description = '%s'", GL, GetErrorText(GL)); 

GetErrorText返回char *,這是屬於錯誤代碼對應的ERRORTEXT功能。

問題是,當我打電話給我的宏時,它不會調用GetErrorText函數。 輸出將是這樣的:RegOpenKeyEx failed. Error code = '5'. Error description = ''

宏定義是這樣的:

#define DEBUG_MESSAGE(Type, debug_message, ...) { _debugLog.message(Type, debug_message, ##__VA_ARGS__); } 

這是函數什麼宏調用:

void log::message(int Type, const char * message, ...) 
    { 
     char MessageExpanded[ 2048 ] = { 0 }; 
     va_list args; 
     int len; 

     write_indentation(); 

     memset(Message, 0, sizeof(Message)); 
     memset(MessageExpanded, 0, sizeof(MessageExpanded)); 

     va_start(args, message); 

     len = _vscprintf(message, args) + 1; // _vscprintf doesn't count terminating '\0' 

     vsprintf_s(Message, len, message, args); 

     va_end(args); 

     sprintf(MessageExpanded, "%s %s", Spaces, Message); 
     LOG(MessageExpanded, context.c_str(), "", Type, CurrentFileName); 

    }//log::message 

是否有解決此問題的方法不知何故?

提前致謝!

更新:

char * GetErrorText(DWORD dwLastError) 
{ 
DEBUG_METHOD(INFO); 
DEBUG_MESSAGE(INFO, "Argument1 = '%d'", dwLastError); 

HMODULE hModule = NULL; // default to system source 
LPSTR MessageBuffer; 
DWORD dwBufferLength; 
char Error[ SMALL ] = { 0 }; 
char * ErrorMsg = NULL; 

DWORD dwFormatFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM; 

// If dwLastError is in the network range, load the message source. 
if (dwLastError >= NERR_BASE && dwLastError <= MAX_NERR) 
{ 
    hModule = LoadLibraryEx(TEXT("netmsg.dll"), NULL, LOAD_LIBRARY_AS_DATAFILE); 
    if (hModule != NULL) dwFormatFlags |= FORMAT_MESSAGE_FROM_HMODULE; 
} 

// Call FormatMessage() to allow for message text to be acquired from the system or from the supplied module handle. 
if (dwBufferLength = FormatMessageA(
             dwFormatFlags, 
             hModule,          // module to get message from (NULL == system) 
             dwLastError, 
             MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // default language 
             (LPSTR)&MessageBuffer, 
             0, 
             NULL 
            ) 
    ) 
{ 
    memset(Error, 0, sizeof(Error)); 
    //printf("\n%s", MessageBuffer); 
    sprintf(Error, "%s", MessageBuffer); 
    ErrorMsg = Error; 

    // Free the buffer allocated by the system. 
    LocalFree(MessageBuffer); 
} 

// If we loaded a message source, unload it. 
if (hModule != NULL) FreeLibrary(hModule); 

return ErrorMsg; 

}//GetErrorText 
+0

難道你不覺得宏定義的宏是如何定義的嗎? –

+0

如何聲明GL? –

+0

@IgorTandetnik:對不起,你說得對,我忘了發佈。 – kampi

回答

2

GetErrorText()返回一個指針到本地緩存:

char Error[ SMALL ] = { 0 }; 

所以它返回的指針是時間_debugLog.message()被稱爲無效。

+0

這可能是一個愚蠢的問題,但我如何正確地返回它? – kampi

+1

@ kampi,你可以使'Error'靜態,但更好的辦法是返回一個'std :: string'。 –

+0

非常感謝,這真的解決了我的問題。 – kampi