[英]Calling Rust from Swift
On the Rust side I wrote a function that returns a String as a pointer of bytes (laid out in memory as a C struct):在 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,
}
}
When generating a header file for it using cbindgen it gives me the following output:使用 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);
In my Xcode project, this header is used as the bridging header, and the shared library compiled from the rust code is added to the dependency list.在我的Xcode项目中,这个头文件作为桥接头文件,将rust代码编译出来的共享库加入到依赖列表中。 The header and include folders are defined in the build properties.标题和包含文件夹在构建属性中定义。
On the swift side I'm calling the rust function the following way:在 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")
}
}
On the line let rustString: RustByteSlice = get_string_from_rust()
, I get the following error:在let rustString: RustByteSlice = get_string_from_rust()
,我收到以下错误:
Cannot convert value of type '__ObjC.RustByteSlice' to specified type 'ed25_ios_app.RustByteSlice'
How can I solve or work around this error ?如何解决或解决此错误?
After working through your code, you are redefining RustByteSlice
.在完成您的代码后,您正在重新定义RustByteSlice
。
From Using Imported C Structs and Unions in Swift , you don't need to redefine it as it automatically imports the struct.从在 Swift 中使用导入的 C 结构和联合,您不需要重新定义它,因为它会自动导入结构。
The below swift code works.下面的快速代码有效。
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.