什么相当于Java中的Marshal.ReadIntPtr(IntPtr)(C#)?

时间:2011-08-03 16:25:58

标签: c# java pointers marshalling

与Java中的Marshal.ReadIntPtr(IntPtr)(C#)相同的是什么?

1 个答案:

答案 0 :(得分:4)

看看下面的课程

sun.misc.Unsafe

该课程的兴趣方法是:

public native long getAddress(long address);
public native void putAddress(long address, long value);
public native long allocateMemory(long size);
public native long reallocateMemory(long l, long l1);
public native void setMemory(long l, long l1, byte b);
public native void copyMemory(long l, long l1, long l2);

这是一个使用它的例子:

import java.lang.reflect.Field;
import sun.misc.Unsafe; 
public class Direct {

        public static void main(String... args) {
            Unsafe unsafe = null;

            try {
                Field field = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
                field.setAccessible(true);
                unsafe = (sun.misc.Unsafe) field.get(null);
            } catch (Exception e) {
                throw new AssertionError(e);
            }

            long value = 12345;
            byte size = 1;
            long allocateMemory = unsafe.allocateMemory(size);
            unsafe.putAddress(allocateMemory, value);
            long readValue = unsafe.getAddress(allocateMemory);
            System.out.println("read value : " + readValue);
        }
    }