Mapping a C Character Containing a Set of Zero-Terminated Function Pointers from Rust to C

I have the following C code that compiled as .so:

void (*vlog_startup_routines[])() = {
    hello_register,
    0
};

In Rust, I can declare functions with #[no_mangle]. How can I put a character under the name vlog_startup_routines, which is an array containing pointers to functions, as well as zero termination?

+4
source share
1 answer

You need to define an element staticwhose type is an array. When defining an element static, unfortunately, we need to specify the size of this array (starting with Rust 1.13.0).

Rust ( unsafe fn). , Rust . : T - ( , ), Option<T> , T 1 None . , Option<fn()>, .

1 Option<T> , T, .

#[no_mangle]
#[allow(non_upper_case_globals)]
pub static vlog_startup_routines: [Option<fn()>; 2] = [
    Some(hello_register),
    None
];

, , , . None Some.

macro_rules! one_for {
    ($_x:tt) => (1)
}

macro_rules! vlog_startup_routines {
    ($($func:expr,)*) => {
        #[no_mangle]
        #[allow(non_upper_case_globals)]
        pub static vlog_startup_routines: [Option<fn()>; $(one_for!($func) +)* 1] = [
            $(Some($func),)*
            None
        ];
    }
}

vlog_startup_routines! {
    hello_register,
}

: one_for , ( , , ), .

+2

Source: https://habr.com/ru/post/1660588/


All Articles