Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I obtain the address of a function?

Tags:

rust

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?

UPD. The answer by @Shepmaster below 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;
like image 395
Jaŭhien Piatlicki Avatar asked Aug 31 '15 22:08

Jaŭhien Piatlicki


1 Answers

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); }
}
like image 119
Shepmaster Avatar answered Oct 06 '22 13:10

Shepmaster