C++ 在 MessageBox 中显示一个函数的地址

标签 c++ visual-c++ memory-address

我试图在 MessageBox 中显示一个函数的内存地址,但它没有按我想要的方式显示。

我想将一个回调函数的函数地址传递给另一个函数,所以我试图获取它的地址。

我看了this示例并尝试先在 MessageBox 中显示它,而不是在使用它之前打印到控制台。

我是如何尝试的:

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;
}

但是,这些消息框显示的数字非常大,而且看起来是空的。

我喜欢在消息框中显示它们,就像在链接帖子的示例输出中一样。

提前致谢。

最佳答案

我对代码做了一些修改,让它更像 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]

关于C++ 在 MessageBox 中显示一个函数的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45749960/

相关文章:

C++ 日志库

Windows 中 UDP 的 C++ 头文件?

c - C++ 枚举类型转换为整数类型后符号不正确

c++ - U后缀的含义

c++ - 合并图中的线性顶点链(在 C++ 中)

Python 变量的地址分配

memory - CPU物理地址空间如何映射到物理DRAM?

python - 为什么Python中的id函数对不同的整型对象返回相同的值?

c++ - 加速 C++(第 3.2.1 节 : vector<double> homework)

C++ Visual Studio 2010 不链接 native 静态库