我正在尝试将this转换为swift。
面对内存分配逻辑的问题
Byte *p[10000];
p[allocatedMB] = malloc(1048576);
memset(p[allocatedMB], 0, 1048576);
如何在swift中写这个?
答案 0 :(得分:3)
你可以使用Swift中的malloc
,它会返回一个“原始指针”:
var p: [UnsafeMutableRawPointer?] = Array(repeating: nil, count: 10000)
var allocatedMB = 0
p[allocatedMB] = malloc(1048576)
memset(p[allocatedMB], 0, 1048576)
或者,使用UnsafeMutablePointer
及其
allocate
和initialize
方法:
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)