Free C-malloc()'d memory in Swift?

后端 未结 1 1635
萌比男神i
萌比男神i 2021-01-13 11:19

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. Th

相关标签:
1条回答
  • 2021-01-13 11:27

    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)
    

    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)
    

    can be simplified to

    let ret = the_function("something")
    
    0 讨论(0)
提交回复
热议问题