简体   繁体   中英

How do I obtain the address of a function?

How do I obtain a function address in Rust? What does '&somefunction' exactly mean?

What addresses do I get doing

std::mem::transmute::<_, u32>(function)

or

std::mem::transmute::<_, u32>(&function)

(on 32-bit system, of course)?

What does

&function as *const _ as *const c_void

give?

If I just wanted to know the address of a function, I'd probably just print it out:

fn moo() {}

fn main() {
    println!("{:p}", moo as *const ());
}

However, I can't think of a useful reason to want to do this. Usually, there's something you want to do with the function. In those cases, you might as well just pass the function directly, no need to deal with the address:

fn moo() {}

fn do_moo(f: fn()) {
    f()
}

fn main() {
    do_moo(moo);
}

I'm less sure about this, but I think that std::mem::transmute::<_, u32>(&function) would just create a local variable that points to function and then gets the reference to that variable. This would match how this code works:

fn main() {
    let a = &42;
}

I need not to work with them in Rust, I need an address because I have some FFI that takes an address of the symbol in the current process

You can still just pass the function as-is to the extern functions that will use the callback:

extern {
    fn a_thing_that_does_a_callback(callback: extern fn(u8) -> bool);
}

extern fn zero(a: u8) -> bool { a == 0 }

fn main() {
    unsafe { a_thing_that_does_a_callback(zero); }
}

The answer by @Shepmaster gives answer to this question (though giving also other not relevant but may be useful for somebody information). I summarize it here.

Obtaining address is easy, just

funct as *const ()

Reference to a function seems to create a local variable just like with

let a = &42;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM