加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 04:41:12 所属栏目:百科 来源:网络整理
导读:我正在使用 Swift编译器的Bridging Header功能来调用使用malloc()分配内存的C函数.然后它返回一个指向该内存的指针.函数原型是这样的: char *the_function(const char *); 在Swift中,我使用它像这样: var ret = the_function(("something" as NSString).UT
我正在使用 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以某种方式处理还是我在这个例子中泄漏内存?

提前致谢.

解决方法

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读