- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我们的项目依赖于一个 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/
我需要用来自 /dev/urandom 的数据填充一个整数类型变量(任意大小)。考虑到这一点,我有以下代码: std::fstream fstr("/dev/urandom", std::fstrea
我是一名优秀的程序员,十分优秀!