chinedufn / swift-bridge

swift-bridge facilitates Rust and Swift interop.
https://chinedufn.github.io/swift-bridge
Apache License 2.0
842 stars 62 forks source link

Swift `Vec<primitive>` Return Type and Function Argument #229

Closed timwedde closed 1 year ago

timwedde commented 1 year ago

Fixes #228.

This enables the following use case:

// Rust
fn main() {
    let bytes = ffi::receive_bytes();
    println!("bytes: {:?}", bytes);

    let vec: Vec<u8> = vec![6, 1, 2, 3, 4, 5];
    ffi::send_bytes(vec);
}

#[swift_bridge::bridge]
mod ffi {
    extern "Swift" {
        fn receive_bytes() -> Vec<u8>;
        fn send_bytes(vec: Vec<u8>);
    }
}
// Swift
func send_bytes(vec: RustVec<UInt8>) {
    print("Received \(vec.len()) bytes from Rust")
    for val in vec {
        print(val)
    }
}

func receive_bytes() -> RustVec<UInt8> {
    let vec = RustVec<UInt8>()
    for i in 0 ... 4 {
        vec.push(value: UInt8(i))
    }
    return vec
}

This is chiefly intended for easy bidirectional byte exchanges but should work for all primitive types, at least the ones I tested with.

The codegen tests pass but I was unable to get the integration tests to run: They also fail for me on master and I don't understand enough of how they work to properly debug them. The (very long) error messages ends with this, which seems to be the culprit:

field has incomplete type 'struct __swift_bridge__$tuple$I32ResultTestOpaqueRustTypeString'

I attempted to add some integration tests for both directions anyway, but given that I'm operating 'blind' on that part I can't assure you whether these work or not.

I'm rather certain that there's still issues with my PR given that this is my first time dealing with this kind of interop work, so by all means do let me know how to address the current weaknesses/problems and I'll do my best to resolve them.

NiwakaDev commented 1 year ago

@timwedde

field has incomplete type 'struct swift_bridge$tuple$I32ResultTestOpaqueRustTypeString'

This error is not due to this PR. If you want to know more detail, please see #225.

It seems like this PR is fine. Thanks!!

timwedde commented 1 year ago

Alright, I think I addressed all of the comments, let me know how I did 👍

chinedufn commented 1 year ago

Thanks!

chinedufn commented 1 year ago

A UI test is failing but I believe it's fixed in #230 so I'll merge this