簡體   English   中英

從 Swift 調用 Rust

[英]Calling Rust from Swift

在 Rust 方面,我編寫了一個函數,該函數返回一個字符串作為字節指針(在內存中作為 C 結構布局):

#[repr(C)]
pub struct RustByteSlice {
    pub bytes: *const u8,
    pub len: size_t,
}

#[no_mangle]
pub extern "C" fn get_string_from_rust() -> RustByteSlice {
    let s = "This is a string from Rust.";
    RustByteSlice {
        bytes: s.as_ptr(),
        len: s.len() as size_t,
    }
}

使用 cbindgen 為它生成頭文件時,它給了我以下輸出:

#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>

typedef struct {
  const uint8_t *bytes;
  size_t len;
} RustByteSlice;

RustByteSlice get_string_from_rust(void);

char *hello(const char *to);

void hello_release(char *s);

void utf8_bytes_to_rust(const uint8_t *bytes, size_t len);

在我的Xcode項目中,這個頭文件作為橋接頭文件,將rust代碼編譯出來的共享庫加入到依賴列表中。 標題和包含文件夾在構建屬性中定義。

在 swift 方面,我通過以下方式調用 rust 函數:

struct RustByteSlice {
    var bytes: UnsafePointer<UInt8>
    var len: Int

    func asUnsafeBufferPointer() -> UnsafeBufferPointer<UInt8> {
        return UnsafeBufferPointer(start: bytes, count: len)
    }
    func asString(encoding: String.Encoding = String.Encoding.utf8) -> String? {
        return String(bytes: asUnsafeBufferPointer(), encoding: encoding)
    }
}

func strPtrRet() {
    let rustString: RustByteSlice = get_string_from_rust()

    if let stringFromRust = rustString.asString() {
        print("got a string from Rust: (stringFromRust)")
    } else {
        print("Could not parse Rust string as UTF-8")
    }
}

let rustString: RustByteSlice = get_string_from_rust() ,我收到以下錯誤:

Cannot convert value of type '__ObjC.RustByteSlice' to specified type 'ed25_ios_app.RustByteSlice'

如何解決或解決此錯誤?

在完成您的代碼后,您正在重新定義RustByteSlice

在 Swift 中使用導入的 C 結構和聯合,您不需要重新定義它,因為它會自動導入結構。

下面的快速代碼有效。

func strPtrRet() -> String? {
    let rustString: RustByteSlice = get_string_from_rust()
    let buffer = UnsafeBufferPointer(start: rustString.bytes, count: rustString.len)
    let string = String(bytes: buffer, encoding: String.Encoding.utf8)

    if let stringFromRust = string {
        print("got a string from Rust: (stringFromRust)")
    } else {
        print("Could not parse Rust string as UTF-8")
    }

    return string
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM