我正在尝试在CUDA中编写类似以下内容的东西(实际上我需要编写一些集成函数)
#include <iostream>
using namespace std;
float f1(float x) {
return x * x;
}
float f2(float x) {
return x;
}
void tabulate(float p_f(float)) {
for (int i = 0; i != 10; ++i) {
std::cout << p_f(i) << ' ';
}
std::cout << std::endl;
}
int main() {
tabulate(f1);
tabulate(f2);
return 0;
}
输出:
0 1 4 9 16 25 36 49 64 81
0 1 2 3 4 5 6 7 8 9
我尝试了以下操作,但只收到了错误信息:
错误:不支持函数指针和函数模板参数在sm_1x中使用。
float f1(float x) {
return x;
}
__global__ void tabulate(float lower, float upper, float p_function(float), float* result) {
for (lower; lower < upper; lower++) {
*result = *result + p_function(lower);
}
}
int main() {
float res;
float* dev_res;
cudaMalloc( (void**)&dev_res, sizeof(float) ) ;
tabulate<<<1,1>>>(0.0, 5.0, f1, dev_res);
cudaMemcpy(&res, dev_res, sizeof(float), cudaMemcpyDeviceToHost);
printf("%f\n", res);
/************************************************************************/
scanf("%s");
return 0;
}
enum F{f1, f2, …}; template<F f> __global__ g(){ switch(f){ case f1: func1(); break; case f2: func2(); break; … }}
然后void h(F f){ switch(f){ case f1: g<f1><<<…>>>(); break; case f2: g<f2><<<…>>>(); break; … } }
。但要注意组合爆炸;如果堆栈足够深,您可能会得到数百兆字节的PTX代码。BT;DT. - datenwolf