Is it possible to alter .NET array allocation method?

时间:2015-09-14 15:40:50

标签: c# .net memory-management cuda

I'm using CUDA via P/Invoke in .NET. In CUDA, they provide a special memory allocation method, which can allocate memory on GPU while in the same time, you can access them from host (of course, unmanaged memory from .NET perspective). This is called unified memory of CUDA which blur the board between CPU and GPU memory.

So, is it possible to alter the default .NET array memory allocation method to a customized unmanaged memory allocation? In that array, I only need to store very simple primitive types such as int, double.

For example, in CUDA C++, they override the new operator to make that class to be seen from both CPU and GPU:

class Managed {
public:
  void *operator new(size_t len) {
    void *ptr;
    cudaMallocManaged(&ptr, len);
    cudaDeviceSynchronize();
    return ptr;
  }

  void operator delete(void *ptr) {
    cudaDeviceSynchronize();
    cudaFree(ptr);
  }
};

1 个答案:

答案 0 :(得分:1)

您无法覆盖C#中的新运算符或更改本机C#数组的行为。但是您可以使用IEnumerable接口和[] -operator实现一个类。因此,您的类将像C#中的本机数组一样运行。

我已经为我的managedCuda库中的Cuda管理内存实现了这一点,这里是GitHub上源代码的直接链接。我还进行了一些性能测试,结果表明,当从主机读取和写入时,cuda管理的内存大约与原始C#数组一样快。

相关问题