问题描述
我正在包装一个较旧的C库,该库要求某些对象在程序执行期间的任何给定时间仅存在一次。
Rust是否有可能在编译时保证结构的这种行为?
或者我应该研究如何创建单例并可能在周围传递Arc<MyWrapperStruct>
?
我已经研究过std::sync::Once
,但这看起来像是一种工具,用于创建类似单例的内容或确保在应用程序生存期内最多发生一次。
可以多次实例化MyWrapperStruct
,但编译器应确保MyWrapperStruct
决不能同时存在(不同线程)或在同一范围内(以某种方式两次)。
MyWrapperStruct
的后续实例是合法的,只要先前的实例已被删除并超出范围。
示例
pub struct MyWrapperStruct<'base> {
pub base: &'base mut libc::c_void,}
impl<'base> MyWrapperStruct<'base> {
pub fn new(logfile: &str) -> MyWrapperStruct<'base> {
let string = CString::new(logfile).unwrap();
let mut base: &mut libc::c_void;
unsafe {
base = &mut *ptr::null_mut();
// c-call here
call_to_c_lib(&mut base,string.as_ptr());
}
MyWrapperStruct { base }
}
}
fn should_not_compile() {
MyWrapperStruct::new("log1.txt");
MyWrapperStruct::new("log2.txt");
}
fn should_compile() {
{
MyWrapperStruct::new("log1.txt");
}
{
MyWrapperStruct::new("log2.txt");
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)