[rust-dev] Building a static array of pointers

Alex Crichton alex at crichton.co
Fri Apr 4 13:06:02 PDT 2014


As you've discovered in bug #13325, dealing with external constants in
static expressions is sometimes a little tricky. I would avoid casting
for now (as happens in the bug) in favor of stronger types. For
example, this compiles and runs for me:

    extern {
        fn foo();
        fn bar();
    }

    static table: &'static [extern unsafe fn()] = &[foo, bar];

    pub mod test {
        #[no_mangle] pub extern fn foo() { println!("foo"); }
        #[no_mangle] pub extern fn bar() { println!("bar"); }
    }

    fn main() {
        for f in table.iter() {
            unsafe { (*f)(); }
        }
    }

Note that in rust, a value of type `extern fn()` cannot be null, but
`Option<extern fn()>` can indeed be null. You'll probably want
something along the lines of:

    #[link_section = ".isr_vector"]
    pub static ISR_VECTOR_TABLE: [Option<extern unsafe fn()>, ..N] =
        [Some(...), None, Some(...), ...];

On Fri, Apr 4, 2014 at 12:53 PM, Vladimir Pouzanov <farcaller at gmail.com> wrote:
> Is it possible to port the following C code to rust?
>
> __attribute__ ((section(".isr_vector")))
> void (* const isr_vector_table[])(void) = {
>     &_stack_base,
>     main,             // Reset
>     isr_nmi,          // NMI
>     isr_hardfault,    // Hard Fault
>     0,                // CM3 Memory Management Fault
>     0,                // CM3 Bus Fault
>     0,                // CM3 Usage Fault
>     &_boot_checksum,  // NXP Checksum code
>     0,                // Reserved
>     0,                // Reserved
>     0,                // Reserved
>     isr_svcall,       // SVCall
>     0,                // Reserved for debug
>     0,                // Reserved
>     isr_pendsv,       // PendSV
>     isr_systick,      // SysTick
> };
>
> here main and isr_* are rust external functions, and _stack_base is defined
> as
>
>   extern void _stack_base()
>
> and gets loaded from linker script.
>
> Also, is it possible to make a weak symbol in rust or somehow emulate it?
> Weak symbols are used in C code to provide the following functionality:
> isr_* functions are stubs with default implementation (morse out id code
> with led, loop forever), but if any of those requires actual code, than it
> is overrides the weak "morse-blinking" function symbol.
>
> --
> Sincerely,
> Vladimir "Farcaller" Pouzanov
> http://farcaller.net/
>
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev
>


More information about the Rust-dev mailing list