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

时间:2022-08-09 21:40:55

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:

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

char *the_function(const char *);

In Swift, I use it like this:

在Swift中,我使用它:

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

let val = String.fromCString(ret)!

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.

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

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

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

Thanks in advance.

提前致谢。

1 个解决方案

#1


5  

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

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)

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

请注意,Swift String在传递给C函数时会自动转换为UTF-8字符串,该函数采用const char *参数,如String值为UnsafePointer 函数参数行为所述。这就是为什么

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

can be simplified to

可以简化为

let ret = the_function("something")

#1


5  

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

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)

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

请注意,Swift String在传递给C函数时会自动转换为UTF-8字符串,该函数采用const char *参数,如String值为UnsafePointer 函数参数行为所述。这就是为什么

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

can be simplified to

可以简化为

let ret = the_function("something")