我想为sn_api库编写一个FFI Package 器,其中包含async
函数。它将用于用Red编写的单线程非异步代码中。
我found,简单的方法是在每个导出的函数中使用Runtime::new().unwrap().block_on(...)
,虽然它涉及到大量创建新的时雄运行时,似乎太重了,无法在每次调用时运行:
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"]
编译的,这似乎不是全局变量的好地方。最好的办法是什么?
4条答案
按热度按时间t5zmwmid1#
我已经决定了一种方法,我创建了一个时雄Runtime,然后将其传递给每个包含异步代码的FFI函数调用:
r8xiu3jd2#
使用静态变量保持运行库对函数调用的可访问性。
8nuwlpux3#
我也面临着同样的问题。这是我的削减:export-tokio-to-lib。
plugin.rs:
lbsnaicq4#
试试这个
由此:
转化为:
参考:https://tokio.rs/tokio/tutorial/hello-tokio#async-main-function