Post

Replies

Boosts

Views

Activity

Data.withUnsafeMutableBytes memory lifetime
I am using Data.withUnsafeMutableBytes to pass a pointer to a C-function which saves the pointer in a struct it returns. Is it safe to assume that as long as my Swift object has a reference to the Data, the pointer will remain valid? Or, might Swift optimize it away? If so, is there any way to insure the data remains available, other than making a copy within the C library? The code is something like this: // read a buffer and save some pointers into it in T_EMsg struct T_EMsg *emsg_read(uint8_t *bytes,size_t length) // assuming "bytes" memory is still available, do some operations with it void emsg_process(T_EMsg *em); class EMsg { var em: UnsafeMutablePointer<T_EMsg>? var data: Data init?(_ data:Data) { self.data = data let count = data.count guard let em = self.data.withUnsafeMutableBytes( { (bytes: UnsafeMutablePointer<UInt8>)->UnsafeMutablePointer<T_EMsg>? in return emsg_read(bytes,count) }) else { return nil } } func process()  { guard let em = em else { return } // is it safe to assume that data memory is still accessible? emsg_process(em) } }
1
0
586
Feb ’21