OpenCL 核心函數支援自訂結構體,但需注意記憶體對齊、主機端與裝置端定義一致性、標量類型對應以及字串不支援等限制。本文透過完整範例展示結構體在 OpenCL 中的正確使用模式。
#include
#include
#include
// 主機端結構體定義
typedef struct StudentNode {
cl_int age; // OpenCL 標量類型對應: cl_int (32-bit 有號整數)
cl_float height; // cl_float (32-bit 浮點數)
} Student;
int main() {
// 分配主機端記憶體
Student *stu_input = (Student*)malloc(sizeof(Student));
Student *stu_output = (Student*)malloc(sizeof(Student));
stu_input->age = 25;
stu_input->height = 1.8f;
// 建立 OpenCL Context、Command Queue、Program、Kernel (略)
// ...
// 建立 Buffer 並傳輸輸入資料
// CL_MEM_COPY_HOST_PTR: 建立時直接複製主機資料
cl_mem inputBuffer = clCreateBuffer(context,
CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR,
sizeof(Student), stu_input, &err);
// 輸出 Buffer (唯寫,不需初始資料)
cl_mem outputBuffer = clCreateBuffer(context,
CL_MEM_WRITE_ONLY,
sizeof(Student), NULL, &err);
// 建立 Kernel
cl_kernel kernel = clCreateKernel(program, "structTest", &err);
// 設定 Kernel 參數 (傳遞 Buffer 物件指標)
clSetKernelArg(kernel, 0, sizeof(cl_mem), &inputBuffer);
clSetKernelArg(kernel, 1, sizeof(cl_mem), &outputBuffer);
// 執行 Kernel (1D, 1 work-item 足夠)
size_t globalSize = 1;
clEnqueueNDRangeKernel(queue, kernel, 1, NULL, &globalSize, NULL, 0, NULL, NULL);
// 讀回結果
clEnqueueReadBuffer(queue, outputBuffer, CL_TRUE, 0, sizeof(Student), stu_output, 0, NULL, NULL);
printf("Output: age=%d, height=%.1f\n", stu_output->age, stu_output->height);
// 預期輸出: age=26, height=1.9
// 清理資源...
}
// 裝置端結構體定義:必須與主機端**記憶體佈局完全一致**
typedef struct StudentNode {
int age; // 對應 cl_int
float height; // 對應 cl_float
} student;
// 輔助函數
int growUp(__global student *stu_input, __global student *stu_output) {
stu_output->age = stu_input->age + 1;
stu_output->height = stu_input->height + 0.1f;
return 0;
}
__kernel void structTest(__global student *stu_input, __global student *stu_output) {
growUp(stu_input, stu_output);
}
OpenCL 裝置端結構體遵循 OpenCL 標量類型對齊規則 (通常為類型大小)。主機端編譯器可能插入填充位元組。
| C/C++ 類型 | OpenCL 類型 | 大小 |
|---|---|---|
int / int32_t | int / cl_int | 4 bytes |
float | float / cl_float | 4 bytes |
double | double / cl_double (需擴展) | 8 bytes |
long long / int64_t | long / cl_long | 8 bytes |
unsigned int | uint / cl_uint | 4 bytes |
char (signed) | char / cl_char | 1 byte |