如何从 CUDA C++ 创建和使用动态库“.so”,并在 Linux 环境 (CentOS) 下在 C# 代码中使用它?

How can I create and use a dynamic library ".so" from CUDA C++ and use it inside C# code under Linux environment (CentOS)?

我正在尝试使用 CUDA C++ 内核创建一个动态库 .so,以便在 C#[ 中使用它=22=] Linux环境下的代码(CentOS)。我搜索了一种方法,但不幸的是没有找到一个完整的解决方案。有些解决方案只包含其中的一部分,例如 creating C++ shared library on Linux, or , but there was no method for creating a dynamic library from CUDA C++. The using of .so created from C++ seamed possible like in this solution.

有没有办法创建这个动态库并在 C# 代码中成功使用它?

在搜索了多种不同的解决方案,并尝试收集和测试可用的可能性后,我终于找到了这个简单的方法。
原始的 C++ 库可以使用 gccthis answer.

一样一步完成
gcc -shared -o dll.so -fPIC dllmain.cpp

但请确保在 .cpp 文件中的所需函数之前添加 extern "C",如下所示:

#include <stdio.h>
extern "C" void func()
{
    // code
}

对于CUDA C++nvcc可以类似this answer and 的方式组合使用。确保使用 .so 而不是 .dll 并使用正确的设备架构,我在这里使用 60 因为我正在使用“Tesla P100-PCIE -16GB".

nvcc -arch=sm_60 --compiler-options '-fPIC' -o dll.so --shared kernel.cu

.cu 文件将与此类似。

#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include <stdio.h>

extern "C" void myfunc(int a, int b, ...);
__global__ void kernel(int a, int b, ...);

__global__ void kernel(int a, int b, ...)
{
    int i = threadIdx.x;
    // kernel code
}

void myfunc(int a, int b, ...)
{
    // code
}

现在动态库 .so 已创建,可以在 C# 代码中使用,如下所示。

using System;
using System.Runtime.InteropServices;
class Program
{
    [DllImport("dll.so")]
    static extern myfunc(int a, int b, ...);

    private void Method()
    {
        int a, b;
        // code
        myfunc(a, b, ...);
    }
}

然后编译C#代码using Mono

mcs Program.cs
mono Program.exe

但可能需要像这样设置所用库的路径。

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/library/

这适用于简单的 CUDA C++ 代码,它可能适用于其他代码,但可能会出现一些问题,具体取决于它们的复杂性。