2011-08-03 42 views

回答

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); 
     } 
    } 
+0

如果我們有一個結構(C++):struct Test { char string1; //「test」// 4 bytes int value1; // 23 // 4 bytes char * label; // * label == 「str」// 4 bytes };如果指向這個結構的指針是「p」(com.sun.jna.Pointer),那麼相當於Marshal.ReadIntPtr(IntPtr)是p.getPointer(8) –

相關問題