Opencl创建程序对象主要有两种方式:由文本文件构建和由二进制文件构建。本文主要给出从文本文件构建程序对象的方法。
从文本文件构建程序对象的API函数是:
extern CL_API_ENTRY cl_program CL_API_CALL
clCreateProgramWithSource(cl_context /* context */,
cl_uint /* count */,
const char ** /* strings */,
const size_t* /* lengths*/,
cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
第一个参数是设备上下文,第二个参数是构建程序对象的个数,第三个参数是源码字符串数组,第四个参数是每一个程序源码文件长度的数组,第五个数错误码。
那么从上面的函数可以看出,要构建一个程序对象首先得创建一个OPencl设备上下文,然后是从文本文件中读取源码内容。
关键是从文本文件读出源码的字符串,下面的代码给出了演示:
char* LoadProgSource(const char* cFilename, const char* cPreamble, size_t* szFinalLength)
{
FILE* pFileStream = NULL;
size_t szSourceLength;
// open the OpenCL source code file
pFileStream = fopen(cFilename, "rb");
if(pFileStream == 0)
{
return NULL;
}
size_t szPreambleLength = strlen(cPreamble);
// get the length of the source code
fseek(pFileStream, 0, SEEK_END);
szSourceLength = ftell(pFileStream);
fseek(pFileStream, 0, SEEK_SET);
// allocate a buffer for the source code string and read it in
char* cSourceString = (char *)malloc(szSourceLength + szPreambleLength + 1);
memcpy(cSourceString, cPreamble, szPreambleLength);
if (fread((cSourceString) + szPreambleLength, szSourceLength, 1, pFileStream) != 1)
{
fclose(pFileStream);
free(cSourceString);
return 0;
}
// close the file and return the total length of the combined (preamble + source) string
fclose(pFileStream);
if(szFinalLength != 0)
{
*szFinalLength = szSourceLength + szPreambleLength;
}
cSourceString[szSourceLength + szPreambleLength] = ‘\0‘;
return cSourceString;
}clBuildProgram(cl_program /* program*/,
cl_uint /*num_devices */,
constcl_device_id * /* device_list*/,
constchar * /* options */,
void(CL_CALLBACK * /* pfn_notify */)(cl_program /* program */,void * /* user_data*/),
void* /*user_data */) CL_API_SUFFIX__VERSION_1_0;
这样内核程序就编译好了,如果编译不成功,会给出一些提示,然后按照规定修改就好了。
下面就是一个简单的调用例子
//装载内核程序 size_t szKernelLength = 0; const char* kernelSourceCode = LoadProgSource(cSourceFile, "", &szKernelLength);
OpenCL从文本文件构建程序对象,布布扣,bubuko.com
原文:http://blog.csdn.net/zhouxuguang236/article/details/21561253