如何找到变量分配的内存?
class app {
public int x = 3;
static void Main(string[] args)
{
}
}
是否可以获取x
变量分配的内存地址?
该示例可以采用 C
、C++
、C#
或 D
语言。 我希望它是清楚的 提前致谢
class app {
public int x = 3;
static void Main(string[] args)
{
}
}
it's possible get the memory address allocated by x
variable?
the example can be in C
, C++
, C#
or D
.
I hope it is clear
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在大多数类 C 语言中,与号 (
&
) 是“取址”运算符:&
的返回值实际上是 指向其操作数的指针。The ampersand (
&
) is the "address-of" operator in most C-like languages:The return value of
&
is effectively a pointer to its operand.在 C 和 C++ 中,这是相当简单的。我将给出 C++ 中的示例:
当然不存在“变量
App::x
”之类的东西,因为App
只是类型< /em>。这种类型的每个实例(例如示例中的a
)都带有自己的一组成员变量,并且很容易获得指向该成员变量的指针。 (C 中的普通数据结构也是如此。)请注意,C++ 还有另一个相关功能:成员指针。这使我们能够形成不透明值
int App::*pm = &App::x
,它本身不指向任何内容,而仅携带有关偏移量的信息 类内的App::x
,如果你愿意的话。该动物可以与实例一起使用来获取实际值,例如a.*pm
.In C and in C++ this is fairly straight-forward. I'll give the example in C++:
There is of course no such thing as "the variable
App::x
", sinceApp
is only the type. Each instance of this type, such asa
in the example, carries its own set of member variables, and a pointer to the member variable is readily obtained. (The same is true for plain data structs in C.)Note that C++ has another, related feature: Member pointers. This allows us to form the opaque value
int App::*pm = &App::x
which by itself doesn't point to anything, but only carries information about the offset ofApp::x
inside the class, if you will. This animal can be used together with an instance to obtain the actual value, e.g.a.*pm
.跳过 D 和 E。C# 和 F#(以及其他 CLR 语言)- 一般而言,任何特定变量都没有固定地址。可以使用托管调试器(即 WinDbg + SOS)来查找任何特定变量的地址,或使用
fixed
以及互操作类。Skipping D and E. C# and F# (and other CLR languages) - there is no fixed addres for any partcular variable in general. One can use managed debugger (i.e. WinDbg + SOS) to find address of any particular variable, or use
fixed
along with interop classes.