【发布时间】:2021-07-09 13:33:32
【问题描述】:
我想为 sn_api 库编写一个 FFI 包装器,其中包含 async 函数。它将用于用 Red 编写的单线程非异步代码。
我found,最简单的方法是在每个导出的函数中使用Runtime::new().unwrap().block_on(...),尽管它涉及大量创建新的 Tokio 运行时并且似乎太重而无法在每次调用时运行:
use std::os::raw::c_char;
use std::ffi::{CString, CStr};
use sn_api::{BootstrapConfig, Safe};
use tokio::runtime::Runtime;
#[no_mangle]
pub extern "C" _safe_connect(ptr: *const Safe, bootstrap_contact: *const c_char) {
assert!(!ptr.is_null());
let _safe = unsafe {
&*ptr
};
let bootstrap_contact = unsafe {
CStr::from_ptr(bootstrap_contact)
}
let mut bootstrap_contacts = BootstrapConfig::default();
bootstrap_contacts.insert(bootstrap_contact.parse().expect("Invalid bootstrap address"));
// how to reuse the Runtime in other functions?
Runtime::new().unwrap().block_on(_safe.connect(None, None, Some(bootstrap_contacts)));
}
是否可以在一个公共 Runtime 上运行所有异步函数?我想这需要创建一些单例/全局,但我的库是用crate-type = ["cdylib"] 编译的,这对于全局来说似乎不是一个好地方。最好的方法是什么?
【问题讨论】:
标签: rust ffi rust-tokio