【问题标题】:Free C-malloc()'d memory in Swift?在 Swift 中释放 C-malloc() 的内存?
【发布时间】:2015-09-10 06:09:38
【问题描述】:

我正在使用 Swift 编译器的桥接头功能调用 C 函数,该函数使用 malloc() 分配内存。然后它返回一个指向该内存的指针。函数原型类似于:

char *the_function(const char *);

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

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

let val = String.fromCString(ret)!

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

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

提前致谢。

【问题讨论】:

    标签: c swift pointers memory-management


    【解决方案1】:

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

    【讨论】:

    • 感谢代码 sn-p!虽然看起来简单明了,但我一开始并不知道该怎么做,因为我不知道 Swift String 初始化程序 copy C 缓冲区。甚至Apple doc 中的示例代码也忘记调用free()。
    猜你喜欢
    • 1970-01-01
    • 2021-04-28
    • 2021-06-15
    • 2016-11-16
    • 2023-02-13
    • 2012-02-07
    • 2014-12-21
    • 1970-01-01
    相关资源
    最近更新 更多