简体   繁体   中英

Corresponding Swift Data types for Metal data types?

I am passing my metal kernel and shader functions a parameter structure. I can't find anywhere that specifies what Swift data types to use to match the data types in Metal.

I have done my best to guess what data types to use on the Swift side, but it seems to be very picky in what order I define the variables in my structs. Which leads me to believe that they are not aligned.

For instance, here are the data types I am using in Metal:

struct ComputeParameters {
    bool yesNo;
    int count;
    float scale;
    float2 point;
    float4 color;
};

And here is my corresponding struct in Swift:

struct ComputeParameters {
    var yesNo: Bool = false
    var count: Int32 = 0
    var scale: Float32 = 1.0
    var point: float2 = float2(0.0, 0.0)
    var color: float4 = float4(0.0, 0.0, 0.0, 1.0)
}

Here is a table of the datatypes I am using from above.

Metal _________ Swift

bool            Bool
int             Int32
float           Float32
float2          float2
float4          float4

Are those correct? Is there somewhere the parameter datatypes are documented?

The size of the Int type in Swift depends on the target platform. It could be equal to Int32 or Int64 , though these days it will almost always be Int64 . So you should use the more explicit Int32 type to match Metal's 32-bit int type.

As of Swift 5, float2 and float4 are deprecated in favor of SIMD2<Float> and SIMD4<Float> , respectively. These correspond exactly with Metal's float2 and float4 .

I believe the rest of your correspondences are correct.

However, it's probably not wise to define these structures in Swift in the first place. Swift gives you no guarantees regarding struct layout (padding, alignment, and member order). Therefore you could wind up with a layout mismatch between Swift and MSL (I haven't seen this happen, but the point is that it can ).

The current guidance, I believe, is to define such structs in C/Objective-C instead and import them via a bridging header. That makes it more likely that memcpy -style copies of structs into Metal buffers will do the right thing. Always pay careful attention to size and alignment, especially since manual reordering of struct members can change the size and/or stride of the struct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM