Reputation: 1695
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
Upvotes: 1
Views: 920
Reputation: 539815
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)
Upvotes: 1