Home > Software engineering >  Apple METAL C problem with MTL::CopyAllDevices();
Apple METAL C problem with MTL::CopyAllDevices();

Time:11-04

I'm trying to get C code working with Metal.

I get the array of MTL:Device by calling

NS::Array *device_array = MTL::CopyAllDevices();

Next, I want to get the only element of the MTL::Device array by calling

MTL::Device *device = device_array->object(0);

I get an error:

Cannot initialize a variable of type 'MTL::Device *' with an rvalue of type 'NS::Object *'

Question:

how to get an MTL::Device object from NS::Array?

CodePudding user response:

NS::Array just contains NS::Objects, it doesn't know what it contains, therefore by default .object(index) returns NS::Object* which is a base class of MTL::Device and therefore not automatically castable. Fortunately object is a template so you can just do:

MTL::Device *device = device_array->object<MTL::Device>(0);

to retrieve the object with the correct class.

Note that this is just implemented with a reinterpret_cast so there is no checking that you've actually used the correct class so use with care!

  • Related