可视C++消息框中函数的显示地址
visual C++ display address of a function in a MessageBox
我正在尝试在消息框中显示函数的内存地址,但它没有按我想要的方式显示它。
我想将回调函数的函数地址传递给另一个函数,所以我试图获取它的地址。
我查看了此示例,并尝试先在 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,现在它似乎可以工作:
- 我正在使用
std::cout
而不是snprintf
打印。 - 我正在通过
std::stringstream
将指针地址转换为std::string
。这对您的MessageBox
应该没有问题。 - 我将函数签名更改为
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++总是显示十六进制内存地址,而不仅仅是整数?
- 我编写了一个程序来显示数组的内容,但它显示的是它的地址
- 为什么我无法显示指针的地址?
- 可视C++消息框中函数的显示地址
- Eclipse 编译器有没有办法将变量中的地址字段显示为整数值?
- GDB 显示损坏的指令地址偏移量
- 如何显示在堆上创建的内存的地址
- 内存地址显示?C++
- C++ 64 位计算机 ,显示 32 位堆地址
- 如何禁用调试控制台在我的代码中显示文件地址
- 本地变量的地址不在smaps显示的堆栈地址范围内
- 更新:程序显示fstream的地址,而不是文本文件
- 终端中未显示内存地址(参考)
- 为什么 printf() 在指针中显示与 cout 不同的地址输出C++
- 显示 IPv6 地址
- FindFirstFile() 显示地址
- GDB:显示函数将我的 {type} 的地址打印为整数——想改成十六进制
- 什么是 dumpbin /import 显示的输入地址表和输入名称表
- GDBstrace显示它试图在一个无效地址ptrace
- c++字符数组不显示地址