指针和malloc在swfit

时间:2018-02-10 21:25:32

标签: swift pointers malloc alloc

我正在尝试将this转换为swift。

面对内存分配逻辑的问题

Byte *p[10000];

p[allocatedMB] = malloc(1048576);
memset(p[allocatedMB], 0, 1048576);

如何在swift中写这个?

1 个答案:

答案 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及其 allocateinitialize方法:

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)