在 windows 上调用 cuda 库

Call cuda library on windows

我正在尝试使用 cuda 并行化一个 Go 项目。 我已经阅读 很多遍了。

我想在 Windows 上做同样的事情,但遇到了麻烦。 (由于 .so 文件,我假设此 OP 使用 Linux)

我已成功compiled/run以下不涉及 cuda 代码的测试程序,以确保我的 CGO 正常工作。

test.cpp

extern "C"{
    int testfunc(){
        return 1000;
    }
}

用 g++ 编译

 g++  test.cpp -o test.dll --shared

callC.go

package main

//int testfunc();
//#cgo LDFLAGS: -L. -ltest
import "C"
import "fmt"

func main() {
    fmt.Println(C.testfunc())
}

打印 1000 - 太棒了!

现在我用 nvcc 尝试同样的事情,但我从 ld 得到一个错误,指出存在对 testfunc 的未定义引用。

test.cu


extern "C"
{
  int testfunc()
  {
    return 1 + 1;
  }
}

编译为 nvcc test.cu -o testcuda.dll --shared --compiler-options -fPIC ...我总是得到:

cl : Command line warning D9002 : ignoring unknown option '-fPIC'
cl : Command line warning D9002 : ignoring unknown option '-fPIC'
cl : Command line warning D9002 : ignoring unknown option '-fPIC'
Creating library testcuda.lib and object testcuda.exp

callCudaC.go

package main

//int testfunc();
//#cgo LDFLAGS: -L. -ltestcuda
//#cgo LDFLAGS: -LC:\temppath\CUDA\v11.2\ -lcudart
import "C"
import "fmt"

func main() {
    fmt.Println(C.testfunc())
}

运行 这个 go 代码的结果是

C:\Users\MICHAE~1\AppData\Local\Temp\go-build045526290\b001\_x002.o: In function `_cgo_701f531a6502_Cfunc_testfunc': /tmp/go-build/cgo-gcc-prolog:52: undefined reference to `testfunc' collect2.exe: error: ld returned 1 exit status

你会注意到我的“cuda”代码不涉及任何 cuda,只有一个导出函数,我尝试将 cuda 安装移动到一个更简单的路径,这样我实际上可以将它作为一个目录传递给链接器- 我不确定是否需要它,因为没有使用 cuda 语法等

如果有人以前看过这个,将不胜感激调试技巧或提示。

感谢@talonmies 评论的指导,我发现至少在简单的情况下,我可以通过定义如下所示的头文件从 cgo 调用由 cl.exe 和 nvcc.exe 创建的 dll :


#ifdef __cplusplus
extern "C" {  // only need to export C interface if
              // used by C++ source code
#endif

 __declspec(dllexport) int  testfunc();
 
#ifdef __cplusplus
}
#endif

此代码是参考以下两篇 MSDN 文章创建的: https://docs.microsoft.com/en-us/cpp/build/exporting-cpp-functions-for-use-in-c-language-executables?view=msvc-160

https://docs.microsoft.com/en-us/cpp/build/exporting-c-functions-for-use-in-c-or-cpp-language-executables?view=msvc-160