2017-08-18 42 views
3

我想在MessageBox中顯示函數的內存地址,但它不會像我想要的那樣顯示它。C++在MessageBox中顯示函數的地址

我想傳遞一個回調函數來另一個函數的函數地址,所以我試圖獲取其地址。

我看着this例如,試圖用一個消息顯示它首先不是打印到控制檯,使用它之前。

我怎麼試了一下:

char ** fun() 
{ 
    static char * z = (char*)"Merry Christmas :)"; 
    return &z; 
} 
int main() 
{ 
    char ** ptr = NULL; 

    char ** (*fun_ptr)(); //declaration of pointer to the function 
    fun_ptr = &fun; 

    ptr = fun(); 

    char C[256]; 

    snprintf(C, sizeof(C), "\n %s \n Address of function: [%p]", *ptr, fun_ptr); 
    MessageBoxA(nullptr, C, "Hello World!", MB_ICONINFORMATION); 

    snprintf(C, sizeof(C), "\n Address of first variable created in fun() = [%p]", (void*)ptr); 
    MessageBoxA(nullptr, C, "Hello World!", MB_ICONINFORMATION); 

    return 0; 
} 

但是,這些消息框顯示非常大的數字,他們似乎空。

我喜歡在鏈接帖子的示例輸出中將它們顯示在一個消息框中。

在此先感謝。

+2

在'(字符*) 「聖誕快樂:)」'中投是無用的,危險的,因爲字符串字面量已經是'常量char *' –

+1

你期望函數指針的值看起來像什麼?我希望有一個「非常大的數字」。你是什​​麼意思,「他們似乎無效」,這似乎與「非常大的數字」相矛盾。 – Yunnosch

+1

*你期望函數指針的值看起來像什麼?*像這樣:'0xxxxxxx'。 :-) **我喜歡將它們顯示在一個消息框中,就像鏈接後的示例輸出一樣。** – Blueeyes789

回答

2

我做的代碼一些變化,使其更c++ -y,現在它似乎工作:

  1. 我使用std::cout打印,而不是snprintf
  2. 我通過std::stringstream將指針地址轉換爲std::string。這應該沒有問題爲您的MessageBox
  3. 我將功能簽名更改爲const char**以避免任何問題。

最終代碼:

#include <iostream> 
#include <sstream> 

const char** fun() 
{ 
    static const char* z = "Merry Christmas :)"; 
    return &z; 
} 
int main() 
{ 
    const char** (*fun_ptr)() = fun; 
    const char** ptr = fun(); 

    std::cout << "Address of function: [" << (void*)fun_ptr << "]" << std::endl; 
    std::cout << "Address of first variable created in fun() = [" << (void*)ptr << "]" << std::endl; 

    std::stringstream ss; 
    ss << (void*)fun_ptr; 
    std::cout << "Address as std::string = [" << ss.str() << "]" << std::endl; 

    return 0; 
} 

輸出:

Address of function: [0x106621520] 
Address of first variable created in fun() = [0x1066261b0] 
Address as std::string = [0x106621520]