忍者ブログ

Memeplexes

プログラミング、3DCGとその他いろいろについて

C#でOpenCL入門 (Cloo版) 非バッファ引数

バッファの参照ではなくintをGPUに渡す

こちらも合わせてお読みください。

ここまでGPUにデータを渡すときはバッファを使っていました。
しかしint一つだけを渡す、なんてこともできます。


サンプルコード

では、GPUにintをひとつ渡すサンプルを見てみましょう。

Program.cs

using Cloo;
using System.Linq;

class Program
{
    static void Main()
    {
        ComputePlatform platform = ComputePlatform.Platforms[0];
        ComputeDevice[] devices = platform
            .Devices
            .Where(d => d.Type == ComputeDeviceTypes.Gpu)
            .ToArray();
        ComputeContext context = new ComputeContext(
            devices,
            new ComputeContextPropertyList(platform),
            null, 
            System.IntPtr.Zero
            );
        ComputeProgram program = new ComputeProgram(
            context,
            System.IO.File.ReadAllText("myKernelProgram.cl")
            );
        program.Build(devices, null, null, System.IntPtr.Zero);
        const int elementCount = 3;
        ComputeBuffer<float> buffer = new ComputeBuffer<float>(
            context, 
            ComputeMemoryFlags.ReadWrite,
            elementCount
            );

        ComputeKernel kernel = program.CreateKernel("myKernelFunction");
        kernel.SetMemoryArgument(0, buffer);
        kernel.SetValueArgument(1, 2);
        ComputeCommandQueue commandQueue = new ComputeCommandQueue(
            context,
            devices[0],
            ComputeCommandQueueFlags.None
            );

        commandQueue.Execute(
            kernel,
            null, 
            new long[] { elementCount },
            new long[] { 1 }, 
            null
            );

        var dataFromGpu = new float[elementCount];
        commandQueue.ReadFromBuffer(
            buffer,
            ref dataFromGpu,
            true,
            null
            );

        foreach (var item in dataFromGpu)
        {
            System.Console.WriteLine(item);
        }

        commandQueue.Dispose();
        kernel.Dispose();
        buffer.Dispose();
        program.Dispose();
        context.Dispose();
    }
}

myKernelProgram.cl

__kernel void myKernelFunction(__global float* items, __const int number)
{
	items[get_global_id(0)] = number;
}

このサンプルプログラムは、まずGPU内にfloatが3つ連なったバッファを確保します。
そしてGPUに2という数字(int)を送ります。
GPUを動かして、2をバッファに代入します。
CPUにバッファの内容を読み戻し、表示します。
結果はこうなります:

2
2
2

拍手[0回]

PR