将对外部C函数的静态函数引用存储在全局静态变量中:类型不匹配:应为fn指针,找到fn项



我需要一个全局静态变量,它引用一个extern "C"函数。

我得到以下编译器错误:

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}`

我的代码在下面或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() {
}

我该如何解决这个问题?

fn类型已经是一个指针(称为"函数指针"(,因此不需要将其放在引用后面:

struct Bar {
foo: unsafe extern "C" fn() -> !,
}

它可以这样创建:

impl Bar {
const fn new(foo: unsafe extern "C" fn() -> !) -> Self {
Self {
foo
}
}
}
static BAR: Bar = Bar::new(foobar);

当您试图编译它时,Rust告诉您const上下文中的函数指针是不稳定的。通过使用Nightly通道并启用const_fn_fn_ptr_basics功能,它可以工作:

游乐场

(这在未来可能会改变,需要时请随时更新此答案(

最新更新