gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 08:59:44 26 4
gpt4 key购买 nike

我想在 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/

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