【问题标题】:How to reinterpret_cast in Swift?如何在 Swift 中重新解释_cast?
【发布时间】:2020-01-18 05:14:03
【问题描述】:

我们的项目依赖于一个 C 库,该库声明了一个通用的 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++ 中的用法示例,在某些情况下,需要将通用的转换为特定的,例如:

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

在 Swift 中是否有类似 reinterpret_cast 的东西?我想我可以手动从payload 读取字节,但我正在寻找一种惯用的方式

【问题讨论】:

  • 查看 UnsafeRawPointer。它具有将原始指针(源自原始类型指针)重新解释为类型指针(新类型)的功能。

标签: swift casting


【解决方案1】:

withMemoryRebound(to:capacity:_:)可以用

...当您有一个指向绑定到一种类型的内存的指针并且您需要将该内存作为另一种类型的实例来访问时。

例子:取通用结构体的地址,然后重新绑定和解引用指针:

let general = GeneralStruct()

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

如果两种类型具有相同的大小和兼容的内存布局,那么您也可以使用unsafeBitCast(_:to:)

仅当无法通过其他方式进行转换时,才能将作为 x 传递的实例转换为布局兼容的类型。

警告:调用此函数会破坏 Swift 类型系统的保证;小心使用。

例子:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 2012-05-11
    • 2013-10-02
    • 2010-10-15
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多