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:
Code Block // c-interfaces
// 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)
}
}



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?

It is clearly documented such usage is unsafe:

withUnsafeMutableBytes(_:)

Warning
The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.

f so, is there any way to insure the data remains available, other than making a copy within the C library? 

You can make a copy within Swift:
Code Block
class EMsg {
var em: UnsafeMutablePointer<T_EMsg>?
var byteBuf: UnsafeMutableBufferPointer<UInt8>
init?(_ data:Data) {
self.byteBuf = .allocate(capacity: data.count)
_ = self.byteBuf.initialize(from: data)
self.em = emsg_read(byteBuf.baseAddress, byteBuf.count);
}
deinit {
byteBuf.deallocate()
//Some code to free em?
//...
}
func process() {
guard let em = em else { return }
emsg_process(em)
}
}


Data.withUnsafeMutableBytes memory lifetime
 
 
Q