本文介绍了Swift中的指针和malloc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将此转换为快速内容.
I am trying to convert this into swift.
面对内存分配逻辑问题
Byte *p[10000];
p[allocatedMB] = malloc(1048576);
memset(p[allocatedMB], 0, 1048576);
如何快速编写此内容?
推荐答案
您可以在Swift中使用malloc
,它会返回原始指针":
You can use malloc
from Swift, it returns a "raw pointer":
var p: [UnsafeMutableRawPointer?] = Array(repeating: nil, count: 10000)
var allocatedMB = 0
p[allocatedMB] = malloc(1048576)
memset(p[allocatedMB], 0, 1048576)
或者,使用UnsafeMutablePointer
及其allocate
和initialize
方法:
Alternatively, use UnsafeMutablePointer
and itsallocate
and initialize
methods:
var p: [UnsafeMutablePointer<UInt8>?] = Array(repeating: nil, count: 10000)
var allocatedMB = 0
p[allocatedMB] = UnsafeMutablePointer.allocate(capacity: 1048576)
p[allocatedMB]?.initialize(to: 0, count: 1048576)
这篇关于Swift中的指针和malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!