gpt4 book ai didi

swift - 如何在 UnsafeMutableRawPointer 处初始化内存

转载 作者:行者123 更新时间:2023-11-28 10:37:10 24 4
gpt4 key购买 nike

我正在使用 UnsafeMutableRawPointer 分配内存:

let p = UnsafeMutableRawPointer.allocate(bytes: 1000, alignedTo: MemoryLayout<UInt8>.alignment)

// do stuff

p.deallocate(bytes: 1000, alignedTo: MemoryLayout<UInt8>.alignment)

分配后,我想初始化内存,即将0x00写入我刚刚分配的所有1000字节。尽管进行了谷歌搜索,但我还是不知道该怎么做。

“做事”是对 C 库的调用,它将一些字节写入指针;我的_c_函数(p)

不幸的是,C 函数希望所有字节都为 NULL。我只有一个静态库,我无法更改 C 代码。

最佳答案

initializeMemory(as:from:count:) :

Initializes the memory referenced by this pointer with the values starting at the given pointer, binds the memory to the values’ type, and returns a typed pointer to the initialized memory.

示例(Swift 4.2):

let p = UnsafeMutableRawPointer.allocate(byteCount: 1000, alignment: MemoryLayout<UInt8>.alignment)
p.initializeMemory(as: UInt8.self, repeating: 0, count: 1000)

// Do stuff ...

p.deallocate()

initializeMemory() 方法返回一个类型指针,以防你需要那个,所以你也可以写

let uint8ptr = p.initializeMemory(as: UInt8.self, repeating: 0, count: 1000)
// UnsafeMutablePointer<UInt8>

关于swift - 如何在 UnsafeMutableRawPointer 处初始化内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52879825/

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