如何在Swift中重新解释? [英] How to reinterpret_cast in Swift?
问题描述
我们的项目依赖于声明通用 struct
Our project depends on a C library that declares a general struct
typedef struct
{
SomeType a_field;
char payload[248];
} GeneralStruct
和更具体的一个:
typedef struct
{
SomeType a_field;
OtherType other_field;
AnotherType another_file;
YetAnotherType yet_another_field;
} SpecificStruct
我们有一些在C ++中使用它的示例,在某些情况下需要将通用对象转换为特定对象,例如:
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)
是否是 reinterpret_cast
在Swift中可用吗?我想我可以手动读取 payload
中的字节,但是我正在寻找一种惯用的方式
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
推荐答案
withMemoryRebound(to:容量:_:)
可以使用
...当您将指向内存的指针绑定到一个
... 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
}
}
如果两种类型具有相同的大小和兼容的内存布局,则还可以使用 unsafeBitCast(_:to:)
:
If both types have the same size and a compatible memory layout then you can also use unsafeBitCast(_:to:)
:
仅当无法通过其他方式进行转换时,才使用此功能将作为x传递的实例转换为与布局兼容的类型。
Use this function only to convert the instance passed as x to a layout-compatible type when conversion through other means is not possible.
警告:调用此函数将破坏Swift类型系统的保证。
Warning: Calling this function breaks the guarantees of the Swift type system; use with extreme care.
示例:
let specific = unsafeBitCast(general, to: SpecificStruct.self)
这篇关于如何在Swift中重新解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!