Golang调用CUDA库 [英] Golang calling CUDA library

查看:78
本文介绍了Golang调用CUDA库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Go代码中调用CUDA函数.我有以下三个文件.

I am trying to call a CUDA function from my Go code. I have the following three files.

test.h:

int test_add(void);

test.cu:

__global__ void add(int *a, int *b, int *c){
       *c = *a + *b;
}

int test_add(void) {
       int a, b, c; // host copies of a, b, c
       int *d_a, *d_b, *d_c; // device copies of a, b, c
       int size = sizeof(int);
       // Allocate space for device copies of a, b, c
       cudaMalloc((void **)&d_a, size);
       cudaMalloc((void **)&d_b, size);
       cudaMalloc((void **)&d_c, size);
      // Setup input values
      a = 2;
      b = 7;

      // Copy inputs to device
      cudaMemcpy(d_a, &a, size, cudaMemcpyHostToDevice);
      cudaMemcpy(d_b, &b, size, cudaMemcpyHostToDevice);
      // Launch add() kernel on GPU
     add<<<1,1>>>(d_a, d_b, d_c);
     // Copy result back to host
     cudaMemcpy(&c, d_c, size, cudaMemcpyDeviceToHost);
     // Cleanup
     cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
    return 0;
}

test.go:

package main

import "fmt"

//#cgo CFLAGS: -I.
//#cgo LDFLAGS: -L. -ltest
//#cgo LDFLAGS: -lcudart
//#include <test.h>
import "C"


func main() {
     fmt.Printf("Invoking cuda library...\n")
     fmt.Println("Done ", C.test_add())
}

我正在使用以下命令编译CUDA代码:

I am compiling CUDA code with:

nvcc -m64 -arch=sm_20 -o libtest.so --shared -Xcompiler -fPIC test.cu

所有三个文件-test.h,test.cu和test.go都位于同一目录中.我尝试使用go构建时遇到的错误是未定义对`test_add'的引用".

All three files - test.h, test.cu and test.go are in the same directory. The error I am getting when I try to build with go is "undefined reference to `test_add'".

我对C/C ++的经验很少,并且是CUDA的新手.

I have very little experience with C/C++ and am a total novice in CUDA.

我已经尝试解决我的问题两天了,非常感谢您的任何投入.

I've been trying to solve my problem for two days now and would be very grateful for any input.

谢谢.

推荐答案

至少在这种情况下,似乎 C 的go import期望该函数提供C样式链接.

It appears, at least in this case, that the go import of C is expecting the function to be provided with C style linkage.

CUDA(即nvcc)主要遵循C ++模式,并默认提供C ++样式链接(包括函数名称修饰等)

CUDA (i.e. nvcc) mainly follows C++ patterns and provides by default C++ style linkage (including function name mangling, etc.)

有可能强制使用C而不是使用 extern"C" {... code ...} 的C ++样式链接在外部提供一段代码.这是C ++语言功能,并非特定于CUDA或nvcc.

It's possible to force a section of code to be provided externally using C rather than C++ style linkage using extern "C" {...code...}. This is a C++ language feature and not specific to CUDA or nvcc.

因此看来,可以通过对test.cu进行以下修改来解决问题:

Therefore it appears the problem can be solved via the following modification to the test.cu:

extern "C" { int test_add(void) { ... code ... }; }

这篇关于Golang调用CUDA库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆