OpenCL编程:创建程序cl_program

在OpenCL中有两个函数负责创建新的程序:clCreateProgramWithSource和clCreateProgramWithBinary。

函数clCreateProgramWithSource要求缓存中的代码是文本形式,其函数原型为:

clCreateProgramWithSource(cl_context context, cl_uint src_num, const char **src_strings, 

const size_t *src_sizes, cl_int *err_code);

函数clCreateProgramWithBinary不是从文本文件中读取字符串,而是二进制文件。

其函数原型为:

clCreateProgramWithBinary(cl_context context, cl_uint num_devices, const cl_device_id *devices, const size_t *bin_sizes,

const unsigned char **bins, cl_int *bin_status, cl_int *err_code);

cl_program program;
FILE *program_handle;
char *program_buffer;
size_t program_size;

err = fopen_s(&program_handle, "add.cl", "r");
if (err < 0)
{
	cout << "Failed to open kernel file." << endl;
	return err;
}
fseek(program_handle, 0, SEEK_END);
program_size= ftell(program_handle);
rewind(program_handle);

program_buffer = (char*)malloc(program_size + 1);
program_buffer[program_size] = '\0';
fread(program_buffer, sizeof(char), program_size, program_handle);
fclose(program_handle);

program = clCreateProgramWithSource(context, 1, (const char**)program_buffer, (const size_t*)&program_size, &err);
if (err < 0)
{
	cout << "Failed to create program with source." << endl;
	return err;
}

add.cl里只做了简单的元素相加。

__kernel void add(__global float *a,
                  __global float *b,
                  __global float *c) {
   
   *c = *a + *b;
}

猜你喜欢

转载自blog.csdn.net/heiheiya/article/details/81086683
cl