The one issue I found is that I’m getting segfaults when returning both Strings and &'static strs.
You’re probably getting segfaults when passing around a
&'static str because that’s a reference to some place embedded in the DLL. Normally a string embedded in a DLL will last the lifetime of the program, but when you are hotswapping the
&'static str actually only lives as long as the DLL is loaded. So if you use a string from a previous version of your DLL (after hotswapping) you’re trying to access data which has been unloaded from memory.
My guess is that you can’t allocate a String on one side of the FFI boundary and drop it on the other - but I’m not really sure why I can’t pass a static str.
I’m not sure why you get segfaults with
String. Out of curiosity, what happens when you explicitly tell the dylib to use the system allocator? I’m not sure how, but it could be that your dylib embedded a copy of jemalloc and then the
String is somehow trying to deallocate itself from that original allocator… Which won’t be in memory any more if you’ve done any hotswapping.
Another thing to look out for is using trait objects. In the past I tried writing a plugin system which loads a DLL, calls a pre-defined “register” function that returns a trait object (e.g.
Box<Plugin>) then after I’d got the plugin I unloaded the DLL (because we don’t need to use it any more). I then spent a good 5 or 10 minutes trying to figure out why I’d get a segfault every time I try to call a method on the trait object. Turns out the trait object vtable points to chunks of code in the DLL it came from… Which I’d already unloaded from memory.
So yeah, make sure your DLL outlives any trait objects or
'static types (which aren’t really
'static in the usual sense) you may get from it.