[英]How can I create and use a dynamic library ".so" from CUDA C++ and use it inside C# code under Linux environment (CentOS)?
我正在嘗試創建一個動態庫.so使用CUDA C++內核在Linux環境 ( CentOS ) 下的C#代碼中使用它。 我尋找了一種方法來做到這一點,但不幸的是沒有找到一個完整清晰的解決方案。 一些解決方案只是其中的一部分,例如在 Linux 上創建 C++ 共享庫,或使用 nvcc 在 CUDA 中創建庫鏈,但沒有從CUDA C++創建動態庫的方法。 使用從C++創建的.so可能就像在這個解決方案中一樣。
有沒有辦法創建這個動態庫並在C#代碼中成功使用它?
在搜索了多種不同的解決方案,並嘗試收集和測試可用的可能性之后,我終於找到了這個簡單的方法。
可以像this answer一樣一步使用gcc制作原始C++庫。
gcc -shared -o dll.so -fPIC dllmain.cpp
但請確保在.cpp文件中所需的函數之前添加extern "C"
,如下所示:
#include <stdio.h>
extern "C" void func()
{
// code
}
對於CUDA C++ , nvcc可以以與此答案和此答案相結合的相同方式使用。 確保使用.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, ...);
}
}
然后使用 Mono編譯C#代碼。
mcs Program.cs
mono Program.exe
但是可能需要像這樣設置使用的庫的路徑。
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/library/
這適用於簡單的CUDA C++代碼,它可能適用於其他代碼,但可能會出現一些問題,具體取決於它們的復雜性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.