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);
}
}
公式の指示では、C ネイティブ関数で char ポインターをマッピングするために、byte[]、char[]、Memory または NIO Buffer を使用すると書かれています。使用する。
出力パラメータ 'lpnSize' は正しいバッファ サイズを返すことができますが、'lpBuffer' は 'x>' (ランダム メモリだと思います) を返すか、Java タイプをマッピングしても何も返しません。最初に 'lpBuffer' メモリに何かを書き込んだ場合、ネイティブ関数を呼び出した後、同じものを読み取ります。
どうすれば問題を解決できますか?