我在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,ptr,arr.Length);
}
return ptr;
}
解决方法
你想使用
Memory
这样使用它:
// 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,arr.length);
请注意,只要将使用内存的本机代码需要它,您就需要保留对Memory对象的强引用(否则,Memory对象将在收集垃圾时回收本机内存).
如果您需要更多地控制本机内存的生命周期,那么请在libc中映射malloc()和free(),然后使用它们.