java 在 jna 中获取字节数组的指针
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5244214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
get pointer of byte array in jna
提问by user206646
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;
}
回答by
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() 并使用它们。