2015-06-24 11 views
5

Sto usando la funzione Bridging Header del compilatore Swift per chiamare una funzione C che alloca la memoria usando malloc(). Quindi restituisce un puntatore a quella memoria. Il prototipo di funzione è qualcosa di simile:Gratuito C-malloc() 'd memoria in Swift?

char *the_function(const char *); 

In Swift, lo uso come questo:

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

let val = String.fromCString(ret)! 

Perdonate la mia ignoranza in materia Swift, ma normalmente in C, se the_function() viene malloc'ing memoria e restituendolo, qualcun altro deve liberarlo() a un certo punto.

Questo è gestito da Swift in qualche modo o sto perdendo memoria in questo esempio?

Grazie in anticipo.

risposta

5

Swift non riesce memoria allocata con malloc(), è necessario liberare la memoria alla fine:

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) 

Nota che uno Swift String viene automaticamente convertito in una stringa UTF-8 quando passò a una funzione C prendendo il parametro come descritto in String value to UnsafePointer<UInt8> function parameter behavior. Ecco perché

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

può essere semplificata

let ret = the_function("something") 
+0

Ha senso, grazie! – Christopher