예제 #1
0
        /// <summary>
        /// Allocated a GPU managed buffer.
        /// Code based on https://www.codeproject.com/Articles/32125/Unmanaged-Arrays-in-C-No-Problem
        /// </summary>
        public IntPtr New(int bytes)
        {
            if (false)
            {
                // Let's try allocating a block of memory on the host. cuMemHostAlloc allocates bytesize
                // bytes of host memory that is page-locked and accessible to the device.
                // Note: cuMemHostAlloc and cuMemAllocHost seem to be almost identical except for the
                // third parameter to cuMemHostAlloc that is used for the type of memory allocation.
                var res = Cuda.cuMemHostAlloc(out IntPtr p, 10, (uint)Cuda.CU_MEMHOSTALLOC_DEVICEMAP);
                if (res == CUresult.CUDA_SUCCESS)
                {
                    System.Console.WriteLine("Worked.");
                }
                else
                {
                    System.Console.WriteLine("Did not work.");
                }
            }

            if (false)
            {
                // Allocate CPU memory, pin it, then register it with GPU.
                int      f       = new int();
                GCHandle handle  = GCHandle.Alloc(f, GCHandleType.Pinned);
                IntPtr   pointer = (IntPtr)handle;
                var      size    = Marshal.SizeOf(f);
                var      res     = Cuda.cuMemHostRegister_v2(pointer, (uint)size, (uint)Cuda.CU_MEMHOSTALLOC_DEVICEMAP);
                if (res == CUresult.CUDA_SUCCESS)
                {
                    System.Console.WriteLine("Worked.");
                }
                else
                {
                    System.Console.WriteLine("Did not work.");
                }
            }

            {
                // Allocate Unified Memory.
                var size = bytes;
                var res  = Cuda.cuMemAllocManaged(out IntPtr pointer, (uint)size, (uint)Swigged.Cuda.CUmemAttach_flags.CU_MEM_ATTACH_GLOBAL);
                if (res != CUresult.CUDA_SUCCESS)
                {
                    throw new Exception("cuMemAllocManged failed.");
                }
                return(pointer);
            }

            if (false)
            {
                return(Marshal.AllocHGlobal(bytes));
            }
        }