Swift: How to use sizeof?

后端 未结 5 1633
逝去的感伤
逝去的感伤 2020-11-29 18:34

In order to integrate with C API\'s while using Swift, I need to use the sizeof function. In C, this was easy. In Swift, I am in a labyrinth of type errors.

I have

5条回答
  •  佛祖请我去吃肉
    2020-11-29 18:46

    Swift 3 now has MemoryLayout.size(ofValue:) which can look up the size dynamically.

    Using a generic function that in turn uses MemoryLayout will have unexpected results if you e.g. pass it a reference of protocol type. This is because — as far as I know — the compiler then has all the type information it needs to fill in the values at compile time, which is not apparent when looking at the function call. You would then get the size of the protocol, not the current value.

提交回复
热议问题