Swift:如何确保代码没有被优化掉?

标签 swift compiler-optimization volatile

我想在 Swift 中将 UnsafeMutablePointer 的内容归零。

在 C 中你通常有这样的东西:

void freeSecure(void *buffer, uint64_t size) {
    // Create volatile pointer to make sure that the code won't be optimized away
    volatile uint8_t *ptr = buffer;
    for (uint64_t i = 0; i < size; i++) ptr[i] = 0x00;
    free(buffer);
}

如何在 Swift 中实现相同的目的?

// Is extension of `UnsafeMutablePointer`
public func KC_dealloc(allocated: Int) {
    if num == 0 {
        self.destroy()
        self.dealloc(allocated)
        return
    }

    let byteCount = sizeof(Memory) * allocated
    let ptr = UnsafeMutablePointer<UInt8>(self) // volatile???
    for var i = 0; i < byteCount; i++ {
        ptr[i] = 0x00
    }
    self.destroy()
    self.dealloc(allocated)
}

最佳答案

好吧,我在 Apple-developer-forum 上问了同样的问题,那里的一些人向我指出了 memset_s-函数,它可以满足我的要求。

所以我的 Swift 代码应该是这样的:

// Is extension of `UnsafeMutablePointer`
public func KC_dealloc(allocated: Int) {
    if num == 0 {
        self.destroy()
        self.dealloc(allocated)
        return
    }

    let byteCount = sizeof(Memory) * allocated
    let ptr = UnsafeMutablePointer<UInt8>(self) // volatile???
    memset_s(ptr, byteCount, 0x00, byteCount) // Defined in C11
    self.destroy()
    self.dealloc(allocated)
}

关于Swift:如何确保代码没有被优化掉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32224740/

相关文章:

ios - 仅观看因缺少 HealthKit info.plist 键而被拒绝的应用程序二进制文件

swift - 将多部分图像、视频和参数发送到服务器时出现问题

swift - 如何通过属性名称设置 Swift 值?

gcc - 从静态可执行文件中剥离未使用的库函数/死代码

C++:如果缺少函数返回语句,for-loop 被优化为无限循环 - 编译器错误?

c++ - 指向 volatile 的指针的迭代器特征

c - 赋值表达式和 volatile

ios - 无法打开用户库中以前的应用程序版本创建的文件

compiler-construction - 位置独立代码和共享对象

java - 没有 static 的 volatile 关键字无法按预期工作