Pointer and malloc in swfit

断了今生、忘了曾经 提交于 2019-12-11 12:29:08

问题


I am trying to convert this into swift.

Facing issue at memory allocation logic

Byte *p[10000];

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

How to write this in swift?


回答1:


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)

Alternatively, use UnsafeMutablePointer and its allocate 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)


来源:https://stackoverflow.com/questions/48725722/pointer-and-malloc-in-swfit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!