在 Metal Objective-C 中将数据复制到 id<MTLBuffer> 或从中复制数据

问题描述 投票:0回答:1

我有以下代码,将数据发送到 MTLBuffer 并从 Objective-C Metal 中的 MTLBuffer 读取。

// header file
@property id<MTLBuffer> memINPUT;
@property id<MTLBuffer> memOUTPUT;

// main file

int length = 1000;
float INPUTVALUE[length];
float RESULTVALUE[length];
for (int i=0; i < length; i++) {
    INPUTVALUE[i] = (float)i;
}

memINPUT = [_device newBufferWithLength:(sizeof(float)*length) options:0];
memOUTPUT = [_device newBufferWithLength:(sizeof(float)*length) options:0];

如何将数据传输到memINPUT并从memOUTPUT读取数据? 我需要迭代多次传输数据。所以MTLBuffer初始时间传输不是一个选择。我尝试使用以下代码将数据复制到缓冲区并从缓冲区读取。我收到编译器错误。请注意,复制部分来自众所周知的示例代码。但不编译。发生类型转换错误。

请注意,我使用以下代码在 Swift 中完成了此操作;


//to copy data to buffer
memINPUT.contents().copyMemory(from: INPUTVALUE, byteCount: length * MemoryLayout<Float>.stride);

// to copy from buffer
float *resultdata = [memOUTPUT contents];
for (int i=0; i < length; i++) {
    RESULTVALUE[i] = resultdata[i];
}

我对此进行了广泛的搜索。但找不到解决方案。预先感谢。

objective-c metal
1个回答
0
投票

要访问

MTLBuffer
的内存,您必须使用
MTLBlitCommandEncoder

类似这样的:

id<MTLCommandQueue> commandQueue = [device newCommandQueue];
id<MTLCommandBuffer> commandBuffer = [commandQueue commandBuffer];
id<MTLBlitCommandEncoder> blitEncoder = [commandBuffer blitCommandEncoder];

[blitEncoder copyFromBuffer: memINPUT \
             sourceOffset: 0 \
             toBuffer: memOUTPUT \
             destinationOffset: 0 \
             size: sizeof(float)*length)];

[blitEncoder endEncoding];
[commandBuffer commit];
[commandBuffer waitUntilCompleted];
© www.soinside.com 2019 - 2024. All rights reserved.