8

I have following code in c# and need similar functionality in java using JNA:

IntPtr pImage = SerializeByteArrayToIntPtr(imageData);

public static IntPtr SerializeByteArrayToIntPtr(byte[] arr)
        {
            IntPtr ptr = IntPtr.Zero;
            if (arr != null && arr.Length > 0)
            {
                ptr = Marshal.AllocHGlobal(arr.Length);
                Marshal.Copy(arr, 0, ptr, arr.Length);
            }
            return ptr;
        }
4
  • @user206646 use System.arrayCopy in java Commented Mar 9, 2011 at 10:32
  • so you want the transfer byte[] into int[], ByteBuffer.asIntBuffer() will probably do what you need. Commented Mar 9, 2011 at 10:38
  • I want pointer ref of the byte[] Commented Mar 9, 2011 at 11:27
  • Is C# byte an unsigned 8-bit integer? It is equivalent to C 8-bit unsigned char. But, Java byte is a 8-bit signed two's complement integer. So, it doesn't match. Probably need to c & 0xFF. For preserving C# reference-type integer parameter, use IntByReference or ByteByReference. More helpful post at stackoverflow.com/questions/333151/… Commented Mar 22, 2011 at 9:22

1 Answer 1

13

You want to use Memory

Use it thusly:

// allocate sufficient native memory to hold the java array
Pointer ptr = new Memory(arr.length);

// Copy the java array's contents to the native memory
ptr.write(0, arr, 0, arr.length);

Be aware, that you need to keep a strong reference to the Memory object for as long as the native code that will use the memory needs it (otherwise, the Memory object will reclaim the native memory when it is garbage collected).

If you need more control over the lifecycle of the native memory, then map in malloc() and free() from libc and use them instead.

Sign up to request clarification or add additional context in comments.

1 Comment

is there any way to say basically a = byte[30]; b = Pointer.fromByteArray(a); ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.