Java:如何像在C ++中一样存储和检索内存地址 [英] Java: How to store and retrieve memory address like in C++

查看:169
本文介绍了Java:如何像在C ++中一样存储和检索内存地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我来自C ++背景.在C ++中,我可以存储我刚刚在全局数组中存储的内存地址,并在以后重新使用它.例如,假设我有两个类X,Y,并且创建了两个对象x,y.全局数组StoreAddresses [2]定义为:

I come from a C++ background. In C++ I can store a memory adress which I just new'd in a global array and re-use it later. For example, say I have two classes X, Y and I create two objects x, y. The global array StoreAddresses[2] is defined as:

 uint32_t StoreAddresses[2];

我写:

 X * x = new X();
 Y * y = new Y();
 StoreAdresses[0] = (uint32t *) x; //for example, 0x12345678
 StoreAdresses[1] = (uint32t *) y; //for example, 0x12345698

在程序的任何地方,我都可以通过调用以下内容来检索写在内存中的数据:

Anywhere in my program, I can retrieve the data written in memory by calling:

 X * stored_x = (X*)StoreAdresses[0];
 Y * stored_y = (Y*)StoreAdresses[1];

如何在Java中完成此操作? 感谢帮助!

How can I accomplish that in Java? Appreciate the help!

推荐答案

您可以使用Unsafe在Java中执行此操作.但是,这是一个非常糟糕的主意.这是因为对象的地址可以随时更改(通过GC),如果您存储这样的地址以供日后使用,则该地址可能不再有效,甚至会使您的应用程序崩溃.如果GC认为某个对象没有强引用,则可以清除该对象.当您尝试再次引用该对象时,它可能不再在JVM中.

You can do this in Java using Unsafe. However its a very bad idea. That is because address of an object can change at any time (by a GC) If you store the address like this an use it later it might not be valid any more and even crash your application. If the GC believes an object does not have a strong reference, it may clean up the object. When you try to reference the object again, it may not be in the JVM any more.

地址的大小可以根据启动JVM的方式而变化. 64位JVM通常使用32位引用(这可能来自C ++).您可以使用Unsafe.ADDRESS_SIZE

The size of an address can change depending on how you start the JVM. A 64-bit JVM usually uses 32-bit references (which might a surprise coming from C++) You can get this with Unsafe.ADDRESS_SIZE

我只会使用Unsafe来查看地址,以查看对象在缓存中的布局方式. (这不是很有用,因为您对此无能为力:()

I would only use Unsafe to see what the addresses are to see how the objects are laid out in your cache. (Which is not very useful as there is not much you can about it :( )

很可能您想做的事都可以做得更好.您能给我们更多细节吗?

It is likely that what ever you are trying to can be done a better way. Can you give us more details?

这篇关于Java:如何像在C ++中一样存储和检索内存地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆