简体   繁体   中英

Marshal.Copy In Java

I'm trying to convert some C# code to java using JNA, and I'm stuck on this last function.

In C# it's known as

Marshal.Copy

This is what I tried so far

byte[] string = new byte[tSecDec.SECItemLen];
Pointer ptr = new Memory(string.length);
ptr.read(tSecDec.SECItemData, string, 0, tSecDec.SECItemLen);
System.out.println(Native.toString(string));

But it didn't work because I get this error

Exception in thread "main" java.lang.IndexOutOfBoundsException: Bounds exceeds available space : size=7, offset=419439024
at com.sun.jna.Memory.boundsCheck(Memory.java:186)
at com.sun.jna.Memory.read(Memory.java:203)

You're allocating tSecData.SECItemLen-1 bytes, and yet you're asking to copy tSecDec.SECItemLen bytes. As the error message indicates, the requested copy bounds exceeds the available (allocated) space.

A) Allocate the full size, don't decrease by one.

B) Use Native.toString(byte[]) to convert the byte array into a Java String .

EDIT

The first argument to Pointer.read() is an offset. For the memory you allocated, if it's anything other than zero, combined with a length of tSecDec.SECItemLen you are going to exceed your allocated memory's boundary (since it was allocated with a length of tSecDec.SECItemLen ).

That code is bogus anyway - you're reading a string out of newly-allocated memory, which at best will give you an empty string (if the memory is zeroed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM