Swift中免费的C-malloc()内存?

Chr*_*her 5 c pointers memory-management swift

我正在使用Swift编译器的Bridging Header功能来调用使用分配内存的C函数malloc().然后它返回一个指向该内存的指针.函数原型是这样的:

char *the_function(const char *);
Run Code Online (Sandbox Code Playgroud)

在Swift中,我使用它像这样:

var ret = the_function(("something" as NSString).UTF8String)

let val = String.fromCString(ret)!
Run Code Online (Sandbox Code Playgroud)

请原谅我对Swift的无知,但通常在C中,如果the_function()是malloc的内存并返回它,那么其他人需要在某个时候释放()它.

这是由Swift以某种方式处理还是我在这个例子中泄漏内存?

提前致谢.

Mar*_*n R 6

Swift不管理分配的内存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)
Run Code Online (Sandbox Code Playgroud)

注意,夫特String传递给取C函数时,自动转换为UTF-8字符串const char *参数中所描述的字符串值到UnsafePointer <UINT8>功能参数行为.这就是为什么

let ret = the_function(("something" as NSString).UTF8String)
Run Code Online (Sandbox Code Playgroud)

可以简化为

let ret = the_function("something")
Run Code Online (Sandbox Code Playgroud)