Swift中的免费C-malloc()内存?
我正在使用Swift编译器的Bridging Headerfunction来调用使用malloc()
分配内存的C函数。 然后它返回一个指向该内存的指针。 函数原型是这样的:
char *the_function(const char *);
在Swift中,我使用它:
var ret = the_function(("something" as NSString).UTF8String) let val = String.fromCString(ret)!
原谅我对Swift的无知,但通常在C中,如果the_function()是malloc的内存并返回它,其他人需要在某个时候释放()它。
这是由Swift以某种方式处理还是我在这个例子中泄漏内存?
提前致谢。
Swift不管理用malloc()
分配的malloc()
,你最终必须释放内存:
let ret = the_function("something") // returns pointer to malloc'ed memory let str = String.fromCString(ret)! // creates Swift String by *copying* the data free(ret) // releases the memory println(str) // `str` is still valid (managed by Swift)
请注意,Swift String
在传递给C函数时会自动转换为UTF-8字符串,该函数采用const char *
参数,如String值为UnsafePointer
let ret = the_function(("something" as NSString).UTF8String)
可以简化为
let ret = the_function("something")