Transfering data to Metal MTLBuffer dynamically in Objective-c

I have a following MTLBuffer created. How can I send INPUTVALUE to the memINPUT buffer? I need to send repeatedly in Objective-C.

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

// main file
int length = 1000;
...
memINPUT = [_device newBufferWithLength:(sizeof(float)*length) options:0];
...
float INPUTVALUE[length];
for (int i=0; i < length; i++) {
	INPUTVALUE[i] = (float)i;
}

// How to send to INPUTVALUE to memINPUT?
...

The following is Swift version. I am looking for Objective-c version.

memINPUT.contents().copyMemory(from: INPUTVALUE, byteCount: length * MemoryLayout<Float>.stride);

Replies

Hi oh1226,

Because your program creates the memINPUT buffer with options 0, Metal allocates it with StorageModeShared, which means that its memory is CPU accessible.

This enables your app to do a direct memcpy from your INPUTVALUE array to your memINPUT buffer:

memcpy(memINPUT.contents, INPUTVALUE, length * sizeof(float));

Since you're using a shared MTLBuffer, keep in mind it may also be an option to directly store your values in the memINPUT and avoid a copy operation altogether.

  • That works nicely. Thanks a lot.

Add a Comment