在 Swift 中释放 C-malloc() 的内存?

Free C-malloc()'d memory in Swift?

我正在使用 Swift 编译器的桥接 Header 功能来调用使用 malloc() 分配内存的 C 函数。然后它 returns 指向该内存的指针。函数原型是这样的:

char *the_function(const char *);

在Swift中,我是这样使用的:

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

let val = String.fromCString(ret)!

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

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

提前致谢。

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")