1

I need a global static variable, that references a extern "C" function.

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

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?

2
  • Funnily enough, when you change it a bit and add an explicit constant in between, you don't get a type error anymore, but “error[E0658]: function pointers cannot appear in constant functions” Commented Jul 15, 2021 at 10:06
  • Also note that in Rust, fn() -> ! is a type useful by itself, you don't need explicit references to make "function pointers": play.rust-lang.org/… Commented Jul 15, 2021 at 10:09

1 Answer 1

3

The fn type is already a pointer (called a "function pointer"), so you don't need to put it behind a reference:

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. By using the Nightly channel and enabling the const_fn_fn_ptr_basics feature, it works:

Playground

(This is likely to change in the future, don't hesitate to update this answer when needed)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.