「OpenCLのソースを外部ファイルから読み込む」で試した外部のOpenCLソースを読み込む機能を「OpenCLをクラスでラップしてみた」、「OpenCLのラッパークラスのドキュメントを書いてみる」で書いたクラスに追加した。
- OpenCL.hpp
#ifndef __OPENCL_HPP__ #define __OPDNCL_HPP__ #if defined(__APPLE__) || defined(__MACOSX) #include <OpenCL/cl.hpp> // For Mac OSX #else #include <CL/cl.hpp> // For Windows/Linux #endif #include <iostream> #if defined(__ENABLE_BOOST__) #include <boost/filesystem/fstream.hpp> #else #include <fstream> #endif namespace DECS{ namespace OpenCL{ #if defined(__ENABLE_BOOST__) typedef boost::filesystem::path PATH; typedef boost::filesystem::ifstream IFSTREAM; #else typedef std::string PATH; typedef std::ifstream IFSTREAM; #endif const cl_device_type DEFAULT_DEVICE_TYPE = CL_DEVICE_TYPE_GPU; class OpenCL{ private: cl_int error_; std::vector platforms_; std::vector devices_; cl::Context context_; cl::CommandQueue queue_; cl::Program::Sources source_; cl::Program program_; cl::Kernel kernel_; std::vector argument_; protected: cl_int setPlatform(); cl_int setContext(); cl_int setContext(cl_device_type deviceType); cl_int setDevice(); public: OpenCL(); OpenCL(cl_device_type deviceType); ~OpenCL(); void setSource(std::string& source); int setSourceFromFile(PATH srcFilePath); cl_int buildProgram(); cl_int setKernel(std::string functionName); cl_int setKernelInputArgument(cl_int index, float* argument, const int n); cl_int setKernelOutputArgument(cl_int index, const int n); cl_int enqueueNDRange(const int n); cl_int readBuffer(cl_int index, float* output, const int n); }; } } #endif // __OPENCL_HPP__
太字部分が今回追加した部分となる。プリプロセッサマクロでBoost C++ Libraryのfilesystemを使用するかどうかを選択できるようにした。"__ENABLE_BOOST__"を定義すると"boost::filesystem"を使用する。定義しない場合は標準ライブラリのstd::stringとstd::ifstreamを使用してソースファイルを読み込む。setSourceFronFileの中身は次のようになっている。
int OpenCL::setSourceFromFile(PATH srcFilePath) { IFSTREAM srcFile(srcFilePath); if(!srcFile){ return 1; } std::string src; std::string buf; while(std::getline(srcFile, buf)){ src.append(buf); } this->setSource(src); return 0; }
前回「OpenCLのソースを外部ファイルから読み込む」で試したものとほとんど変更はない。関数内部でsetSourceを呼び出し、プライベート変数にソースを保存している。
この変更を含むすべてのソースはこちら→ DECS_OpenCL_20120414をダウンロード
前回の「OpenCLのラッパークラスのドキュメントを書いてみる」で書いたドキュメントには既に含まれている。
コメント