简体   繁体   English

在jna中获取字节数组的指针

[英]get pointer of byte array in jna

I have following code in c# and need similar functionality in java using JNA: 我在c#中有以下代码,并且在使用JNA的java中需要类似的功能:

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). 请注意,只要将使用内存的本机代码需要它,您就需要保留对Memory对象的强引用(否则,Memory对象将在收集垃圾时回收本机内存)。

If you need more control over the lifecycle of the native memory, then map in malloc() and free() from libc and use them instead. 如果您需要更多地控制本机内存的生命周期,那么请在libc中映射malloc()和free(),然后使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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