How to reinterpret_cast in Swift?

左心房为你撑大大i 提交于 2020-05-14 03:57:53

问题


Our project depends on a C library that declares a general struct

typedef struct
{
  SomeType a_field;
  char payload[248];
} GeneralStruct

and a more specific one:

typedef struct
{
  SomeType a_field;
  OtherType other_field;
  AnotherType another_file;
  YetAnotherType yet_another_field;
} SpecificStruct

We have some examples of its usage in C++ and in some cases it's needed to cast the general one to the specific one like:

GeneralStruct generalStruct = // ...
SpecificStruct specificStruct = reinterpret_cast<SpecificStruct&>(generalStruct)

Is it something like reinterpret_cast available in Swift? I guess I could read the bytes from payload manually, but I'm looking for an idiomatic way


回答1:


withMemoryRebound(to:capacity:_:) can be used

... when you have a pointer to memory bound to one type and you need to access that memory as instances of another type.

Example: Take the address of the general struct, then rebind and dereference the pointer:

let general = GeneralStruct()

let specific = withUnsafePointer(to: general) {
    $0.withMemoryRebound(to: SpecificStruct.self, capacity: 1) {
        $0.pointee
    }
}

If both types have the same size and a compatible memory layout then you can also use unsafeBitCast(_:to:):

Use this function only to convert the instance passed as x to a layout-compatible type when conversion through other means is not possible.

Warning: Calling this function breaks the guarantees of the Swift type system; use with extreme care.

Example:

let specific = unsafeBitCast(general, to: SpecificStruct.self)


来源:https://stackoverflow.com/questions/57972556/how-to-reinterpret-cast-in-swift

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!