添加 CUDA dll 作为对显示错误的 C# 项目的引用
我已经制作了一个简单的 CUDA dll,代码如下所示。该函数向数组添加一些值。
#include<stdio.h>
#include<stdlib.h>
#include<cuda.h>
//Cuda Kernel
__global__ void add_gpu(float *a)
{
int idx=blockIdx.x*blockDim.x+threadIdx.x;
a[idx]=a[idx]*2;
}
int cudasafe( cudaError_t error)
{
if(error!=cudaSuccess)
return 1;
else
return 0;
}
extern "C" int __declspec(dllexport) __stdcall add_gpu_cu(float *a, int size,int nblock, int nthread)
{
float* dev_a;
int flag;
flag=cudasafe(cudaMalloc((void**)&dev_a,size*sizeof(float)));
if(flag==1)
return flag;
flag=cudasafe(cudaMemcpy(dev_a,a,size*sizeof(float),cudaMemcpyHostToDevice));
if(flag==1)
return flag;
add_gpu<<<10,10>>>(dev_a);
flag=cudasafe(cudaMemcpy(a,dev_a,size*sizeof(float),cudaMemcpyDeviceToHost));
if(flag==1)
return flag;
}
问题是我无法将创建的 dll 添加为对我的 c# 项目的引用。它抛出一个异常,表示无法添加对该文件的引用。确保该文件可访问,并且它是有效的程序集或 COM 组件。
我在创建 dll 时做错了什么吗?
请帮忙
问候
I have made a Simple CUDA dll the code which I am displaying below. The function adds some value to an array.
#include<stdio.h>
#include<stdlib.h>
#include<cuda.h>
//Cuda Kernel
__global__ void add_gpu(float *a)
{
int idx=blockIdx.x*blockDim.x+threadIdx.x;
a[idx]=a[idx]*2;
}
int cudasafe( cudaError_t error)
{
if(error!=cudaSuccess)
return 1;
else
return 0;
}
extern "C" int __declspec(dllexport) __stdcall add_gpu_cu(float *a, int size,int nblock, int nthread)
{
float* dev_a;
int flag;
flag=cudasafe(cudaMalloc((void**)&dev_a,size*sizeof(float)));
if(flag==1)
return flag;
flag=cudasafe(cudaMemcpy(dev_a,a,size*sizeof(float),cudaMemcpyHostToDevice));
if(flag==1)
return flag;
add_gpu<<<10,10>>>(dev_a);
flag=cudasafe(cudaMemcpy(a,dev_a,size*sizeof(float),cudaMemcpyDeviceToHost));
if(flag==1)
return flag;
}
The problem is I cant add the dll created as a reference to my c# project. It throws up an exception saying a reference to the file could not be added. Make sure the file is accessible, and that its a valid assembly or COM component.
Am i doing something wrong in creating the dll?
Please help
Regards
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,该 DLL 是 C++ DLL,而不是 .NET DLL,因此您无法添加对它的引用。您需要使用互操作才能在 C# 中使用它。
为此,您需要在 DLL(或 __declspec)中包含一个 .DEF 文件以使函数可导出,然后按照以下方式在 C# 中声明定义:
No, the DLL is a C++ DLL, and not a .NET DLL, so you can't add a reference to it. You need to use interop to use it in C#.
To do so, you need to include a .DEF file in your DLL (or the __declspec) to make the function exportable, then declare the definition in C# along the lines of:
引用必须是托管DLL,即它必须使用MSIL 编写。您当前使用非托管库。 这里是一个很酷的教程,介绍如何从。网。
Reference must be a managed DLL, i.e. it must be written with MSIL. You use unmanaged library currently. Here's a cool tutorial on making unmanaged calls from .NET.