Reputation: 101
I want to make program in C# that will use external C/C++ CUDA library.
I'm still newbie on this. I heard that I can add external DLL in my code.
I just want to parse output image from the CUDA function, i don't want to use device pointers in the C# layer.
Is this possible, if so how I can achieve this?
Cheers
Upvotes: 2
Views: 912
Reputation: 747
One way to do it is to write a C++ dll application using which ever CUDA library you want to use and then call the functions exposed through the dll from C# code. This would mean you are entering into the unmanaged world, which is tricky if multiple threads come into the picture.
C++ DLL code, the following goes into a header, you would have to implement body in a cpp file.
#ifndef __MYFUNC_H__
#define __MYFUNC_H__
#if defined MYFUNC_EXPORT
#define EXPOSE_API __declspec(dllexport)
#else
#define EXPOSE_API __declspec(dllimport)
#endif
\\ better to have namespace to avoid conflicts with other libs
namespace myspace
{
EXPOSE_API void myCall(const float * const array, const int numelements);
}
#endif
C# code would like something like the following:
[DllImport("myfunc.dll",EntryPoint="?myCall@CUnmanagedTestClass@@QAEXH@Z",CallingConvention=CallingConvention.ThisCall)]
static public extern void myCall(float* array, int numelements);
I believe, the above statement shoud be written in all .cpp files where ever you want to use this function.
Also, the crazy string you might have observed in "EntryPoint" attribute is the mangled name of the function with parameters encoded. You don't need to understand what it is, you just need to put it in entry point. Get dependency walker from http://www.dependencywalker.com/ and open the dll you just created, you would have to browse through a little but that would give you this mangled name of the function exposed through your dll.
That's it, that is how i did it when using ArrayFire (CUDA/OpenCL library for GPU based computations) for one of our client who uses C#. It works fine but i had to put unsafe and fixed statements encompassing these function calls in C# so that the memory is not moved around while the function is working on it.
I bet there are multiple ways of doing it, but this one keeps all unwanted things within the function call (CUDA) and when the function returns the result is in CPU memory space.
Upvotes: 2