[英]Coding CUDA with C#?
I've been looking for some information on coding CUDA (the nvidia gpu language) with C#. 我一直在寻找有关使用C#编写CUDA(nvidia gpu语言)的一些信息。 I have seen a few of the libraries, but it seems that they would add a bit of overhead (because of the p/invokes, etc).
我已经看到了一些库,但似乎它们会增加一些开销(因为p / invokes等)。
There is such a nice complete cuda 4.2 wrapper as ManagedCuda . 有一个很好的完整的cuda 4.2包装作为ManagedCuda 。 You simply add C++ cuda project to your solution, which contains yours c# project, then you just add
您只需将C ++ cuda项目添加到您的解决方案中,其中包含您的c#项目,然后您只需添加
call "%VS100COMNTOOLS%vsvars32.bat"
for /f %%a IN ('dir /b "$(ProjectDir)Kernels\*.cu"') do nvcc -ptx -arch sm_21 -m 64 -o "$(ProjectDir)bin\Debug\%%~na_64.ptx" "$(ProjectDir)Kernels\%%~na.cu"
for /f %%a IN ('dir /b "$(ProjectDir)Kernels\*.cu"') do nvcc -ptx -arch sm_21 -m 32 -o "$(ProjectDir)bin\Debug\%%~na.ptx" "$(ProjectDir)Kernels\%%~na.cu"
to post-build events in your c# project properties, this compiles *.ptx file and copies it in your c# project output directory. 要在c#项目属性中构建事件,这将编译* .ptx文件并将其复制到c#项目输出目录中。
Then you need simply create new context, load module from file, load function and work with device. 然后,您只需创建新的上下文,从文件加载模块,加载功能和使用设备。
//NewContext creation
CudaContext cntxt = new CudaContext();
//Module loading from precompiled .ptx in a project output folder
CUmodule cumodule = cntxt.LoadModule("kernel.ptx");
//_Z9addKernelPf - function name, can be found in *.ptx file
CudaKernel addWithCuda = new CudaKernel("_Z9addKernelPf", cumodule, cntxt);
//Create device array for data
CudaDeviceVariable<cData2> vec1_device = new CudaDeviceVariable<cData2>(num);
//Create arrays with data
cData2[] vec1 = new cData2[num];
//Copy data to device
vec1_device.CopyToDevice(vec1);
//Set grid and block dimensions
addWithCuda.GridDimensions = new dim3(8, 1, 1);
addWithCuda.BlockDimensions = new dim3(512, 1, 1);
//Run the kernel
addWithCuda.Run(
vec1_device.DevicePointer,
vec2_device.DevicePointer,
vec3_device.DevicePointer);
//Copy data from device
vec1_device.CopyToHost(vec1);
This has been commented on the nvidia list in the past: 这已在过去的nvidia列表中评论过:
http://forums.nvidia.com/index.php?showtopic=97729 http://forums.nvidia.com/index.php?showtopic=97729
it would be easy to use P/Invoke to use it in assemblies like so: 使用P / Invoke很容易在程序集中使用它,如下所示:
[DllImport("nvcuda")]
public static extern CUResult cuMemAlloc(ref CUdeviceptr dptr, uint bytesize);
There are several alternatives you can use to use CUDA in your C# applications. 您可以使用几种方法在C#应用程序中使用CUDA。
You can find several of them online : have a look at this answer for example. 您可以在线找到其中几个:例如,看一下这个答案 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.