mozilla / uniffi-rs

a multi-language bindings generator for rust
https://mozilla.github.io/uniffi-rs/
Mozilla Public License 2.0
2.48k stars 211 forks source link

Accessing Vec<u8> in swift #2159

Closed parthdt closed 1 week ago

parthdt commented 1 week ago

How do I use a object in rust with a field of bytes: Vec<u8> in swift? How is this handled by uniffi?

I have:


#[derive(uniffi::Object)]
pub struct FzilInput
{
    pub bytes: Vec<u8>
}

impl FzilInput
{
    #[uniffi::constructor]
    pub fn new(bytes: *const u8, len: usize) -> Self {
        // Convert raw pointer and length to Vec<u8>
        let bytes = unsafe { std::slice::from_raw_parts(bytes, len).to_vec() };
        Self { bytes }
    }
}

uniffi::setup_scaffolding!();

Now, I'm running into multiple unsafeFromRawPointer errors while directly trying to access a [UInt8].

And this:

import pc // Import the generated Swift module

// Swift representation of bytes
let bytes: [UInt8] = [1, 2, 3, 4, 5]

// Convert Swift array to UnsafeMutablePointer<UInt8>
let bytePointer = UnsafeMutablePointer<UInt8>.allocate(capacity: bytes.count)
bytePointer.initialize(from: bytes, count: bytes.count)

// Call the Rust constructor via Uniffi
let input = FzilInput(unsafeFromRawPointer: bytePointer)

bytePointer.deallocate()

Gives me:

JIT session error: Symbols not found: [ $s2pc9FzilInputC20unsafeFromRawPointerACSv_tcfC, $s2pc9FzilInputCMa ]
Failed to materialize symbols: { (main, { main, $s4test11bytePointerSpys5UInt8VGvp, $ss27_finalizeUninitializedArrayySayxGABnlF, $s4test5bytesSays5UInt8VGvp, $sSa12_endMutationyyF, $s4test5input2pc9FzilInputCvp }) }

Please help!

mhammond commented 1 week ago

As I noted in #2158, our test at https://github.com/mozilla/uniffi-rs/tree/main/fixtures/coverall has extensive coverage of "bytes", so that can probably point you in the right direction.

parthdt commented 1 week ago

Hi Mark,

Thanks a lot for pointing me towards the tests for bytes. Using Data() for bytes helped. Thanks a ton!