About lifetimes

Hi, I'm playing with FFI and I need to know how to manage correctly some lifetimes. Let's take an example :
alias external_func = fn(UnsafePointer[JpegErrorMgr]) -> UInt

@value
struct Stuff:
var pointer : UnsafePointer[UInt8]
var ... # many other fields

fn main():
var thing = ffi.DLHandle("liblambda.so", ffi.RTLD.NOW)
if thing.__bool__():
var bytes = List[UInt8]()
with open("file", "rb") as f:
bytes = f.read_bytes()

var my_struct = Stuff()
my_struct.pointer = bytes.unsafe_ptr()
var result = thing.get_function[external_func]("external_func")(my_struct.unsafe_ptr())
# others call to external_func but no other use of my_struct
...
alias external_func = fn(UnsafePointer[JpegErrorMgr]) -> UInt

@value
struct Stuff:
var pointer : UnsafePointer[UInt8]
var ... # many other fields

fn main():
var thing = ffi.DLHandle("liblambda.so", ffi.RTLD.NOW)
if thing.__bool__():
var bytes = List[UInt8]()
with open("file", "rb") as f:
bytes = f.read_bytes()

var my_struct = Stuff()
my_struct.pointer = bytes.unsafe_ptr()
var result = thing.get_function[external_func]("external_func")(my_struct.unsafe_ptr())
# others call to external_func but no other use of my_struct
...
If I understand correctly, for Mojo, the life of bytes stops as soon as my_struct is not used and in this case, it's just after the first call to "external_func". Trouble is external_func will need bytes to be alive for a longer time but Mojo can't know that and external_func will starts to act funny because the values of bytes may have changed So, my question is : how to manage this kind of lifetime ? an easy answer is to do some useless stuff with my_struct at the end of the block or encapsulate some parts in a function (it's what I do now), but a cleaner way to do that must exists. I've also try to use DTypePointer but I have only be able to use them with basic types like a bunch of bytes but not structured data I must have misunderstood something.
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server