无C-的malloc()在雨燕'D内存? [英] Free C-malloc()'d memory in Swift?

查看:111
本文介绍了无C-的malloc()在雨燕'D内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是斯威夫特编译器的桥接报头的功能调用,使用的malloc分配内存的C函数()。然后,它返回一个指向该内存。该函数的原型是这样的:

I'm using the Swift compiler's Bridging Header feature to call a C function that allocates memory using malloc(). It then returns a pointer to that memory. The function prototype is something like:

char *the_function(const char *);

在斯威夫特,我用它是这样的:

In Swift, I use it like this:

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

let val = String.fromCString(ret)!

请原谅我关于雨燕,但通常在C,如果the_function()被malloc'ing内存还,别人需要释放(),它在某个时候。

Forgive my ignorance concerning Swift but normally in C, if the_function() is malloc'ing memory and returning it, somebody else needs to free() it at some point.

这是由雨燕莫名其妙地处理还是我在这个例子中内存泄露?

Is this being handled by Swift somehow or am I leaking memory in this example?

先谢谢了。

推荐答案

斯威夫特不管理与分配的内存的malloc(),最终你必须要释放内存

Swift does not manage memory that is allocated with malloc(), you have to free the memory eventually:

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)


请注意,一个斯威夫特字符串被自动转换为UTF-8
当传递给C函数取为const char * 参数字符串
在<一个描述href=\"http://stackoverflow.com/questions/27063569/string-value-to-unsafepointeruint8-function-parameter-behavior\">String价值UnsafePointer&LT;&UINT8 GT;功能参数的行为。
这就是为什么


Note that a Swift String is automatically converted to a UTF-8 string when passed to a C function taking a const char * parameter as described in String value to UnsafePointer<UInt8> function parameter behavior. That's why

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

可以简化为

let ret = the_function("something")

这篇关于无C-的malloc()在雨燕'D内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆