我可以从非 nvcc 编译的 C++ 代码中调用 CUDA 运行时函数吗?
有什么方法可以调用 CUDA 运行时函数调用,例如
Is there any way I can call CUDA runtime function calls such as
cudaMemcpy(...);
在 .cpp 文件中,使用常规 C++ 编译器编译?
in a .cpp file, compiled with a regular C++ compiler?
推荐答案
有一个 这里的例子但是已经找不到了,不过大部分例子都复制到下面了.
There was an example here but it's not longer found, but most of the example was copied below.
调用者 C(但可能是 C++)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <cuda.h>
extern void kernel_wrapper(int *a, int *b);
int main(int argc, char *argv[])
{
int a = 2;
int b = 3;
kernel_wrapper(&a, &b);
return 0;
}
被调用者 (CUDA)
__global__ void kernel(int *a, int *b)
{
int tx = threadIdx.x;
switch( tx )
{
case 0:
*a = *a + 10;
break;
case 1:
*b = *b + 3;
break;
default:
break;
}
}
void kernel_wrapper(int *a, int *b)
{
int *d_1, *d_2;
dim3 threads( 2, 1 );
dim3 blocks( 1, 1 );
cudaMalloc( (void **)&d_1, sizeof(int) );
cudaMalloc( (void **)&d_2, sizeof(int) );
cudaMemcpy( d_1, a, sizeof(int), cudaMemcpyHostToDevice );
cudaMemcpy( d_2, b, sizeof(int), cudaMemcpyHostToDevice );
kernel<<< blocks, threads >>>( a, b );
cudaMemcpy( a, d_1, sizeof(int), cudaMemcpyDeviceToHost );
cudaMemcpy( b, d_2, sizeof(int), cudaMemcpyDeviceToHost );
cudaFree(d_1);
cudaFree(d_2);
}
相关文章