/// <summary> /// Uses GCHandle to allocated pinned allocate pinned chunks of memory in CPU host memory. /// </summary> /// <param name="accelerator">The current accelerator.</param> /// <param name="dataSize">The number of elements to copy.</param> static void PerformPinnedCopyUsingGCHandle(Accelerator accelerator, int dataSize) { var array = new int[dataSize]; var handle = GCHandle.Alloc(array, GCHandleType.Pinned); try { // Allocate buffer on this device using (var bufferOnGPU = accelerator.Allocate1D <int>(array.Length)) { var stream = accelerator.DefaultStream; // Page locked buffers enable async memory transfers using (var scope = accelerator.CreatePageLockFromPinned(array)) { bufferOnGPU.View.CopyFromPageLockedAsync(stream, scope); // // Perform other operations... // // Wait for the copy operation to finish stream.Synchronize(); } } } finally { handle.Free(); } }
public void PinnedUsingGCAllocateArray() { var expected = Enumerable.Repeat(42, Length).ToArray(); var array = System.GC.AllocateArray <int>(Length, pinned: true); using var buffer = Accelerator.Allocate1D <int>(array.Length); using var scope = Accelerator.CreatePageLockFromPinned(array); buffer.View.CopyFromPageLockedAsync(scope); Execute(buffer.Length, buffer.View); buffer.View.CopyToPageLockedAsync(scope); Accelerator.Synchronize(); Verify1D(array, expected); }
/// <summary> /// Uses System.GC.AllocateArray to allocated pinned allocate pinned chunks of memory in CPU host memory. /// </summary> /// <param name="accelerator">The current accelerator.</param> /// <param name="dataSize">The number of elements to copy.</param> static void PerformPinnedCopyUsingGCAllocateArray(Accelerator accelerator, int dataSize) { var array = GC.AllocateArray <int>(dataSize, pinned: true); // Allocate buffer on this device using var bufferOnGPU = accelerator.Allocate1D <int>(array.Length); var stream = accelerator.DefaultStream; // Page locked buffers enable async memory transfers using var scope = accelerator.CreatePageLockFromPinned(array); bufferOnGPU.View.CopyFromPageLockedAsync(stream, scope); // // Perform other operations... // // Wait for the copy operation to finish stream.Synchronize(); }
public unsafe void PinnedUsingGCHandle() { var expected = Enumerable.Repeat(42, Length).ToArray(); var array = new int[Length]; var handle = GCHandle.Alloc(array, GCHandleType.Pinned); try { using var buffer = Accelerator.Allocate1D <int>(array.Length); using var scope = Accelerator.CreatePageLockFromPinned(array); buffer.View.CopyFromPageLockedAsync(scope); Execute(buffer.Length, buffer.View); buffer.View.CopyToPageLockedAsync(scope); Accelerator.Synchronize(); Verify1D(array, expected); } finally { handle.Free(); } }