twall/jna — Issue #34: When ByteBuffer.wrap(byte[] bts,int offset, int len) the offset gets ignored
Author: nyholku
Created: 2011-10-31 12:07:36+00:00
State: open

Following self contained example demonstrates the issue:

Instead of the expected result:

----------------------------------
11
****Hello World***
----------------------------------

we get

----------------------------------
11
Hello World*********
----------------------------------

the code:

import java.nio.ByteBuffer;

import com.sun.jna.*;

public class Test {
static Win32APILibrary lib = (Win32APILibrary) Native.loadLibrary("kernel32", Win32APILibrary.class);

public interface Win32APILibrary extends Library { Pointer CreateFileA(String fn, int access, int mode, Pointer sec, int create, int atts, Pointer tmplt); boolean WriteFile(Pointer h, ByteBuffer buf, int nw, int[] nwn, Pointer olp); boolean ReadFile(Pointer h, ByteBuffer bud, int nr, int[] nrn, Pointer olp); boolean CloseHandle(Pointer hFile); }

final static int GENERIC_READ = 0x80000000;

final static int GENERIC_WRITE = 0x40000000;

final static int GENERIC_EXECUTE = 0x20000000;

final static int GENERIC_ALL = 0x10000000;

final static int CREATE_NEW = 1;

final static int CREATE_ALWAYS = 2;

final static int OPEN_EXISTING = 3;

public static void main(String[] args) {
{
boolean ok;
Pointer h = lib.CreateFileA("test.txt", GENERIC_WRITE, 0, null, CREATE_NEW, 0, null);
ByteBuffer out = ByteBuffer.wrap("Hello World".getBytes());
int[] outn = { 0 };
ok = lib.WriteFile(h, out, out.capacity(), outn, null);
ok = lib.CloseHandle(h);
}

{
boolean ok;
Pointer h = lib.CreateFileA("test.txt", GENERIC_READ, 0, null, OPEN_EXISTING, 0, null);
byte [] bts="********************".getBytes();
ByteBuffer in = ByteBuffer.wrap(bts,5,11);
int[] inn = { 0 };
ok = lib.ReadFile(h, in, in.capacity(), inn, null);
ok = lib.CloseHandle(h);
System.out.println(inn[0]);
System.out.println(new String(in.array()));
}

}
}