Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

memcpy function in C++ to Java equivalent

Tags:

java

c++

I have in C++

memcpy (&wkpm, (PMSK *)pr_masks + (long)(x - 1), sizeof(PMSK)); 

where PMSK is a struct. It will be a class in Java.

Now assuming that here I am copying the whole chunk of memory into pr_masks i.e creating an additional instance of the PMSK class. How to do this in Java.

Example: In a java code at line 20 I want capture the class instance and then again use that same instance in line 100. In between there may be many modifications.

Hope I am clear with my question.

Thanks

like image 855
JavaBits Avatar asked May 19 '11 14:05

JavaBits


2 Answers

In Java you need to either do a shallow clone() of the object or copy every field individually. There is no low level, make one object a copy of another object.

like image 134
Peter Lawrey Avatar answered Oct 17 '22 10:10

Peter Lawrey


Java actually does have something just like memcpy(). The Unsafe class has a copyMemory() method that is essentially identical to memcpy(). Of course, like memcpy(), it provides no protection from memory overlays, data destruction, etc. It is not clear if it is really a memcpy() or a memmove(). It can be used to copy from actual addresses to actual addresses or from references to references. Note that if references are used, you must provide an offset (or the JVM will die ASAP).

Unsafe.copyMemory() works (up to 2 GB per second on my old tired PC). Use at your own risk. Note that the Unsafe class does not exist for all JVM implementations.

You should also take a look at "Tricks with Direct Memory Access in Java" (http://highlyscalable.wordpress.com/2012/02/02/direct-memory-access-in-java/) and "Java Magic. Part 4: sun.misc.Unsafe" (memcpy function in C++ to Java equivalent) for some additional ideas. These guys are deeply versed in how to do low level (and risky) operations in Java.

like image 31
Peter Schaeffer Avatar answered Oct 17 '22 11:10

Peter Schaeffer