gpt4 book ai didi

swift - 如何在 Swift 中重新解释_cast?

转载 作者:行者123 更新时间:2023-11-28 05:38:04 26 4
gpt4 key购买 nike

我们的项目依赖于一个 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 中读取字节,但我正在寻找一种惯用的方式

最佳答案

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

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

示例:获取通用结构的地址,然后重新绑定(bind)并取消引用指针:

let general = GeneralStruct()

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

如果两种类型具有相同的大小和兼容的内存布局,那么您还可以使用 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.

例子:

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

关于swift - 如何在 Swift 中重新解释_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57972556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com