魔法师の高塔

Metal的C++封装

boost::compute用c++封装了opencl,我正读他的代码,结构条理令人愉悦。

metal的代码是objc与swift原生的,但objc可以兼容c++代码,所以把metal按boost::compute的方式封装起来,对自己也是一个锻炼,看boost::compute的结构,我设计的metal::compute会有device、command_queue等结构。GPU上的数据可以封装为vector,std::vector应该可以与metal::compute::vector交换数据。metal文件里写的函数,就是operator,基本的运算可以重载。

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using compute = metal::compute;
int main(int argc, char const * argv[]) {
// get default device and setup command queue
compute::device device = compute::system::default_device();
compute::context context(device);
compute::command_queue queue(context,device);
// create vector on host
unsigned len = 5;
std::vector<int> host_vector1 = {1,3,5,6,7};
// create vector on device
compute::vector<int> device_vector1(len,context);
compute::vector<int> device_vector2(len,context);
compute::vector<int> device_vector3(len,context);
// copy data from host to device
compute::copy(host_vector.begin(), host_vector.end(), device_vector1.begin(),context);
// fill data to device vector
compute::fill(device_vector2.begin(),device_vector2.end(), rand);
// add operator
device_vector3 = device_vector2 + device_vector1;
std::cout<<device_vector3[2]<<std::endl;
return 0;
}