这个问题是关于CUDA C / C ++编程的。我尝试了很多搜索,但是没有找到合适的问题,因此也没有回答。
我有1个设备功能,1个内核功能和主要功能:
typedef float (*pfunc)(float arg);
__device__ float dev_func(float arg) {
return arg * arg;
}
__global__ void ker_func(pfunc fnc) {
printf("%f\n", fnc(2));
}
int main(void) {
pfunc fnc = dev_func;
//now how do I copy this pointer to device memory?
ker_func<<<1,1>>>(...);
return 0;
}
__global__
主机代码中使用的功能的地址不能在设备代码中使用(例如,启动内核)。同样,__global__
设备代码中使用的功能的地址不能在主机代码中使用。不允许使用
__device__
主机代码中的函数地址。
因此,您有两种选择:
__device__
全局定义函数指针,然后在内核中调用它。
typedef float (*pfunc)(float arg);
__device__ float dev_func(float arg) {
return arg * arg;
}
// create device function pointer here
__device__ pfunc dev_func_ptr = dev_func;
__global__ void ker_func() {
// call function through device function pointer
printf("%f\n", dev_func_ptr(2));
}
如果要将函数指针传递给内核作为参数,则:
#define gpuErrchk(val) \
cudaErrorCheck(val, __FILE__, __LINE__, true)
void cudaErrorCheck(cudaError_t err, char* file, int line, bool abort)
{
if(err != cudaSuccess)
{
printf("%s %s %d\n", cudaGetErrorString(err), file, line);
if(abort) exit(-1);
}
}
typedef float (*pfunc)(float arg);
__device__ float dev_func(float arg) {
return arg * arg;
}
// create device function pointer here
__device__ pfunc dev_func_ptr = dev_func;
__global__ void ker_func(pfunc fnc) {
// call function through device function pointer
printf("%f\n", fnc(2));
}
int main(int argc, char** argv)
{
// create a host function pointer
pfunc host_function_ptr;
// copy function pointer value from device to host
gpuErrchk(cudaMemcpyFromSymbol(&host_function_ptr, dev_func_ptr, sizeof(pfunc)));
// pass the copied function pointer in kernel
ker_func<<<1,1>>>(host_function_ptr);
gpuErrchk(cudaPeekAtLastError());
gpuErrchk(cudaDeviceSynchronize());
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句