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;
        }
Anders
  • 8,307
  • 9
  • 56
  • 88
user206646
  • 191
  • 1
  • 3
  • 9
  • @user206646 use System.arrayCopy in java – Dead Programmer Mar 09 '11 at 10:32
  • so you want the transfer byte[] into int[], ByteBuffer.asIntBuffer() will probably do what you need. – bestsss Mar 09 '11 at 10:38
  • I want pointer ref of the byte[] – user206646 Mar 09 '11 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 http://stackoverflow.com/questions/333151/java-how-to-pass-byte-by-reference – eee Mar 22 '11 at 09:22

1 Answers1

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.

smbear
  • 1,007
  • 9
  • 17