«

»

Oct 04

Embedding OpenCL Kernel Files in the Application on Windows

OpenCL kernel files are often a hindrance in writing generic code because they lead to the use of absolute paths in the application. One can overcome this issue on Linux by using relative paths. However on Windows, visual studio is not very friendly to the use of relative paths. One way to solve this problem on Windows is to use Resources and the steps for doing are enumerated below.

  • Right-click on “Resource Files” in Visual Studio solution explorer and add a resource. A resource file (.rc) will now be added to the project. Open the .rc file and delete all its contents and just write the following in it:
RESFILE KERNELSOURCE "Kernels.cl"

RESFILE and KERNELSOURCE are just two keywords, and you can use whatever you want. Kernels.cl is your kernel file and it should be present in the $(SOLUTIONDIR).

  • In the .cpp file, include Windows.h. To convert the resource file to a string so that it can passed to clCreateProgramWithSource(), do the following:
HRSRC res = FindResource(nullptr, "RESFILE", "KERNELSOURCE"); // find the resource
HGLOBAL glob = LoadResource(nullptr, res);  // load the resource.
const char *textPtr = (char *)LockResource(glob); // lock the resource to get a char*
DWORD textSize = SizeofResource(nullptr, res); // get the size of the resource
std::string text(textPtr, textSize); // form a string for the resource file.
  • The above five lines can be compressed into two by:
HRSRC res = FindResource(nullptr, "RESFILE", "KERNELSOURCE");
std::string text = std::string((char *)LockResource(LoadResource(nullptr, res)), SizeofResource(nullptr, res));
  • To create the OpenCL program (clCreateProgramWithSource), one needs a char* pointer. Therefore, we need to convert std::string to char*, which can be done by:
const char *buf = text.c_str();
  • clCreateProgramWithSource can be called as follows:
cl_program program = clCreateProgramWithSource(myGPUContext, 1, buf, NULL, NULL);

The application is now free from all the absolute paths and can be run on any machine without any problems.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>