Brendonovich / swift-rs

Call Swift functions from Rust with ease!
Apache License 2.0
246 stars 28 forks source link

fix: NSObject offset size in SRObject being too small #60

Open hampustagerud opened 3 months ago

hampustagerud commented 3 months ago

Hi!

Thank you for this library, it have made mixing Rust and Swift a breeze!

However, I encountered a bug when I tried to implement a function which returned a class with 4 ints. The first member of the class always got the same weird number. It seems like the memory offset used in SRObject is not big enough, only taking up one byte whereas a pointer (on 64-bit systems) is 8 bytes.

Replacing the u8 offset with *const c_void seems to solve this issue as Rust now allocates the size for a pointer instead of just a byte. The test I also added replicates my issue and fails with the u8 type but passes after the change 🙂

Brendonovich commented 3 months ago

From some reading it appears you're correct, each NSObject contains a pointer. I'm curious why existing examples continued to work without this though, also I now realise that I haven't accounted for alignment of individual fields at all 😅

hampustagerud commented 3 months ago

Why it worked before is a mystery to me too, I have no idea really 😅

I used the Swift REPL which printed the layout of the object, not too sure how to get it otherwise outside of xcode 🙂

repl class

It looks the same for all classes I define so it really shouldn't work. Maybe there is some compiler magic at work that aligns the structure differently depending on what fields are defined in the class and by pure luck it has worked? 😄