开发者

Adding a CUDA dll as a reference to a C# project showing an error

开发者 https://www.devze.com 2023-04-05 04:06 出处:网络
I have made a Simple CUDA dll the code which I am displaying below. The function adds some value to an array.

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开发者_StackOverflow中文版,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


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:

[DllImport("your_dll_name")]  public static extern int add_gpu_cu(IntPtr a, int size, int nblock, int ntrheac);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消