[英]Store static function reference to extern C function in global static var: mismatched types: expected fn pointer, found fn item
我需要一個全局靜態變量,它引用一個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
功能,它可以工作:
(這在未來可能會改變,在需要時不要猶豫更新這個答案)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.