2013-06-27 64 views
0
public interface Kernel32 extends StdCallLibrary { 

    int GetComputerNameW(Memory lpBuffer, IntByReference lpnSize); 
} 

public class Kernel32Test { 

    private static final String THIS_PC_NAME = "tiangao-160"; 

    private static Kernel32 kernel32; 

    @BeforeClass 
    public static void setUp() { 
    System.setProperty("jna.encoding", "GBK"); 
    kernel32 = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class); 
    } 

    @AfterClass 
    public static void tearDown() { 
    System.setProperty("jna.encoding", null); 
    } 

    @Test 
    public void testGetComputerNameW() { 
     final Memory lpBuffer = new Memory(1024); 
     final IntByReference lpnSize = new IntByReference(); 

     final int result = kernel32.GetComputerNameW(lpBuffer, lpnSize); 

     if (result != 0) { 
      throw new IllegalStateException(
      "calling 'GetComputerNameW(lpBuffer, lpnSize)'failed,errorcode:" + result); 
     } 

     final int bufferSize = lpnSize.getValue(); 
     System.out.println("value of 'lpnSize':" + bufferSize); 
     Assert.assertEquals(THIS_PC_NAME.getBytes().length + 1, bufferSize); 

     final String name = lpBuffer.getString(0); 
     System.out.println("value of 'lpBuffer':" + name); 
     Assert.assertEquals(THIS_PC_NAME, name); 
    } 
} 

offical instructions說,使用字節[]的char [],內存或NIO緩衝區映射字符指針在C本地function.But我嘗試了所有的上面,和字符串, WString,StringArrays,類擴展PointType等,它們都沒有用。如何讓JNA回讀功能的字符串結果

Out參數'lpnSize'可以返回corret緩衝區大小,但'lpBuffer'返回'x>'(我認爲它是隨機存儲器)或者不管我映射任何Java類型。如果我寫了一些'lpBuffer '首先,它會在調用native函數後讀取相同的內容。

我該如何解決問題?

回答

2

您需要使用Pointer.getString(0, true)來提取由GetComputerNameW返回的unicode字符串。

編輯

您還需要與函數之前初始化長度參數再次調用GetComputerNameW將結果填寫。將相同的IntByReference傳回第二個呼叫,或將IntByReference初始化爲您的Memory緩衝區的大小,以在第一個呼叫中寫入緩衝區。

+0

問題是本地函數只是不寫lpBuffer內存,不管調用'GetComputerNameA'或'GetComputerNameW'。 – user2527513