Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save babon/0054f226175302420c62824386ac4d4a to your computer and use it in GitHub Desktop.
Save babon/0054f226175302420c62824386ac4d4a to your computer and use it in GitHub Desktop.
public class MMFNativeArray<T> where T : struct
{
MemoryMappedFile mmf;
MemoryMappedViewAccessor accessor;
public NativeArray<T> native;
public MMFNativeArray(string path, FileMode mode, string mapName, int bytes)
{
unsafe
{
mmf = MemoryMappedFile.CreateFromFile(path, mode, mapName, bytes);
//Note that if you call CreateViewAccessor with offset you must add that offset to the pointer from AcquirePointer. AcquirePointer refers to the beginning of the file regardless of the offset in CreateViewAccessor.
accessor = mmf.CreateViewAccessor(0, bytes);
byte* ptr = null;
accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref ptr);
native = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(ptr, bytes / UnsafeUtility.SizeOf<T>(), Allocator.None);
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref native, AtomicSafetyHandle.Create());
}
}
public void Dispose()
{
native.Dispose();
accessor.SafeMemoryMappedViewHandle.ReleasePointer();
accessor.Dispose();
mmf.Dispose();
}
}
//usage:
//directly saves from gpu to file
AsyncGPUReadback.RequestIntoNativeArray(ref mmf.native, computeBuffer);
//directly loads from file to gpu
computeBuffer.SetData(mmf.native);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment