简体   繁体   中英

get pointer of byte array in jna

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;
        }

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.

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