我想使用Zero Copy方法将二进制文件读取到OpenCL内存对象。但是,当我的代码执行readFile时,我的程序已停止工作。
我已阅读其他Q& A,
但是,我还没有解决我的问题。
这是我的代码
//OPENCL Include
#include <CL/cl.h>
typedef float2 cplx;
int readFile(char *filen, cplx* data);
int main(int argc, char* argv[])
{
char *filename = (char*)malloc(100);
sprintf(filename,"%s",argv[1]);
//OpenCL Structures
cl_device_id device;
cl_context context;
cl_command_queue commandQueue;
int err;
int filesize = 1024;
device = create_device();
context = clCreateContext(NULL, 1, &device, NULL, NULL, &err);
if(err < 0)
{
perror("Couldn't create a context");
exit(1);
}
commandQueue = clCreateCommandQueue(context, device, 0, &err);
if(err < 0)
{
perror("Couldn't create Command Queue");
exit(1);
}
cl_mem memObj_data[1] = {0};
size_t buffer_size = 1024 * sizeof(cplx);
printf("Create Buffer\n");
memObj_data[0] = clCreateBuffer(context, CL_MEM_READ_WRITE | CL_MEM_ALLOC_HOST_PTR, buffer_size, NULL, &err);
if(err != CL_SUCCESS)
{
cerr << getErrorString(err) << endl;
exit(1);
}
// cplx *data = (cplx*)malloc(sizeof(cplx)*sizeFile);
// data = (cplx*)clEnqueueMapBuffer(commandQueue, memObj_data[0], CL_TRUE, CL_MAP_WRITE, 0, buffer_size, 0, NULL, NULL, &err);
printf("Enqueue Map Buffer\n");
cplx* data = (cplx*)clEnqueueMapBuffer(commandQueue, memObj_data[0], CL_TRUE, CL_MAP_WRITE, 0, buffer_size, 0, NULL, NULL, &err);
if(err != CL_SUCCESS)
{
cerr << getErrorString(err) << endl;
exit(1);
}
int ret = readFile(filename, data);
if(ret == 1)
{
cout << "Error on Reading File" << endl;
return 1;
printf("Enequeue Unmap Memory Object\n");
err = clEnqueueUnmapMemObject(commandQueue, memObj_data[0], data, 0, NULL, NULL);
if(err != CL_SUCCESS)
{
cerr << getErrorString(err) << endl;
exit(1);
}
//Deallocate resource
clReleaseMemObject(memObj_data[0]);
clReleaseCommandQueue(commandQueue);
clReleaseContext(context);
clReleaseDevice(device);
//FREE MEMORY
delete[] filename;
return 0;
}
int readFile(char *filen, cplx* data)
{
cout << "Read File" << endl;
//Get size contains of file
// ifstream file("../testfile", ios::in | ios::binary | ios::ate);
streampos size;
char path[20];
sprintf(path,"%s",filen);
ifstream file(path, ios::in | ios::binary | ios::ate);
if(file.is_open())
{
size = file.tellg();
// *data = (cplx*)realloc(*data, sizeof(cplx)*size);
if(size)
{
// data = data;
cout << "Read CFL file Success" << endl;
}
else
{
cout << "Error Allocating Memory" << endl;
return 1;
}
cout << "Contains Size : "<< std::to_string(size) << endl;
}
else
{
cout << "Unable to open file";
return 1;
}
if(file.is_open())
{
file.seekg(0, ios::beg);
file.read((char*)data, size);
file.close();
}
// int start = 230;
// int finish = 250;
// cout << "ON Functions" << endl;
// for(int i = start; i < finish; i++)
// {
// cout << i << " "<< std::to_string((*data)[i].x) << " + " << std::to_string((*data)[i].y) << endl;
// }
// data = memblock;
// free(memblock);
return 0;
}
然后,在读取二进制文件时,我的程序已停止工作。