[英]Store static function reference to extern C function in global static var: mismatched types: expected fn pointer, found fn item
I need a global static variable, that references a extern "C"
function.我需要一个全局静态变量,它引用一个extern "C"
函数。
I get the following compiler error:我收到以下编译器错误:
error[E0308]: mismatched types
--> src/main.rs:17:28
|
17 | static BAR: Bar = Bar::new(&foobar);
| ^^^^^^^ expected fn pointer, found fn item
|
= note: expected reference `&'static unsafe extern "C" fn() -> !`
found reference `&unsafe extern "C" fn() -> ! {foobar}`
My code down below or on Rust playground我的代码在下面或Rust 操场上
extern "C" {
fn foobar() -> !;
}
struct Bar {
foo: &'static unsafe extern "C" fn() -> !
}
impl Bar {
const fn new(foo: &'static unsafe extern "C" fn() -> !) -> Self {
Self {
foo
}
}
}
static BAR: Bar = Bar::new(&foobar);
fn main() {
}
How can I solve this?我该如何解决这个问题?
The fn
type is already a pointer (called a "function pointer"), so you don't need to put it behind a reference: fn
类型已经是一个指针(称为“函数指针”),所以你不需要把它放在引用后面:
struct Bar {
foo: unsafe extern "C" fn() -> !,
}
It can be created like this:它可以像这样创建:
impl Bar {
const fn new(foo: unsafe extern "C" fn() -> !) -> Self {
Self {
foo
}
}
}
static BAR: Bar = Bar::new(foobar);
When you try to compile this, Rust tells you that function pointers in const
contexts are unstable.当你尝试编译它时,Rust 会告诉你const
上下文中的函数指针是不稳定的。 By using the Nightly channel and enabling the const_fn_fn_ptr_basics
feature, it works:通过使用Nightly频道并启用const_fn_fn_ptr_basics
功能,它可以工作:
(This is likely to change in the future, don't hesitate to update this answer when needed) (这在未来可能会改变,在需要时不要犹豫更新这个答案)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.