在Swift中免费使用C-malloc()'内存?

时间:2015-06-24 07:01:19

标签: c swift pointers memory-management

我使用Swift编译器的Bridging Header功能来调用使用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以某种方式处理还是我在这个例子中泄漏了内存?

提前致谢。

1 个答案:

答案 0 :(得分:5)

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)

请注意,Swift String会自动转换为UTF-8 传递给带有const char *参数的C函数的字符串 如String value to UnsafePointer<UInt8> function parameter behavior中所述。 这就是

的原因
let ret = the_function(("something" as NSString).UTF8String)

可以简化为

let ret = the_function("something")