我想将一个字符串传递给我的GPU并从GPU中取回来打印它.这是为了理解目的 - 我知道,这个想法听起来毫无意义.
我试过了:
OpenCL的:
__kernel void same_in_same_out_char(__global uchar * out, __constant uchar * in){
for (unsigned int ui=0; ui<3; ui++) out[ui]=in[ui];
}
Run Code Online (Sandbox Code Playgroud)
C++:
#define __CL_ENABLE_EXCEPTIONS
#include <fstream>
#include <iostream>
#include <iterator>
#include <CL/cl.hpp>
#include <CL/opencl.h>
using namespace std;
int main () {
vector<cl::Platform> platforms;
vector<cl::Device> devices;
vector<cl::Kernel> kernels;
try {
// create platform
cl::Platform::get(&platforms);
platforms[0].getDevices(CL_DEVICE_TYPE_GPU, &devices);
// create context
cl::Context context(devices);
// create command queue
cl::CommandQueue queue(context, devices[0]);
// load opencl source
ifstream cl_file("inout.cl");
string cl_string(istreambuf_iterator<char>(cl_file), (istreambuf_iterator<char>()));
cl::Program::Sources source(1, make_pair(cl_string.c_str(),
cl_string.length() + 1));
// create program
cl::Program program(context, source);
// compile opencl source
program.build(devices);
// load named kernel from opencl source
cl::Kernel kernel(program, "same_in_same_out_char");
// create a message to send to kernel
const char pwd[] = "MAX";
cout << "char pwd[] : " << pwd << endl;
cl_uchar * password = (cl_uchar*) &pwd;
int bufferA_size = 3; // array size is 3
int bufferC_size = 3; // array size is 3
cout << " -- OpenCL -- " << endl;
// allocate device buffer to hold message
cl::Buffer bufferA(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uchar) * bufferA_size, password);
cl::Buffer bufferC(context, CL_MEM_WRITE_ONLY, sizeof(cl_uchar) * bufferC_size);
// set message as kernel argument
kernel.setArg(0, bufferC);
kernel.setArg(1, bufferA);
// execute kernel
queue.enqueueTask(kernel);
// wait for completion
queue.finish();
// ----------------------
cl_uint out_global[bufferC_size];
queue.enqueueReadBuffer(bufferC, CL_TRUE, 0, bufferC_size*sizeof(cl_uchar), &out_global);
cout << "Output \t\t:" << *out_global << endl << "Output[1..n] \t:";
for (unsigned int i=0; i<bufferC_size; i ++) cout << out_global[i] << " " ;
cout << endl;
} catch (cl::Error e) {
cout << endl << e.what() << " : " << e.err() << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但我失败了.输出是
产量:5783885
输出[1..n]:5783885 0 26
但不是
MAX或77 65 88
(对于MAX).
关注,马库斯
如果事实上给你你想要的答案,但你把它放在错误的数据类型.
你得到的是单个整数5783885,它是0x0058414D(十六进制).你是在一个小端平台上,所以这些字节在内存中从低位到高位排列,即如果你看看内存,字节将是(仍为十六进制):
4D, 41, 58, 00, ...
Run Code Online (Sandbox Code Playgroud)
以十进制显示的这些将是:
77, 65, 88, 0, ...
Run Code Online (Sandbox Code Playgroud)
换句话说,正是你所期望的.
您的问题(你的问题之一,至少)是你已经声明out_global为数组cl_uintS,而不是cl_uchar或cl_char什么的.
所以改变以下行,你可能会没事的.
cl_uint out_global[bufferC_size];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1210 次 |
| 最近记录: |