How to get the address of a function?

How to get function address in Rust? What does "& somefunction" exactly mean?

What addresses do I get

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

or

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

(on a 32-bit system, of course)?

What is he doing

 &function as *const _ as *const c_void 

gives?

UPD The answer from @Shepmaster below gives an answer to this question (although it gives others that are not relevant, but may be useful for someone's information). I summarize it here.

Getting an address is easy, simple

 funct as *const () 

The function reference seems to create a local variable similar to

 let a = &42; 
+5
source share
1 answer

If I just wanted to know the address of the function, I would just print it:

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

However, I cannot come up with a useful reason to want to do this. Usually there is something you want to do with a function. In such cases, you can just simply 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 not sure about this, but I think that std::mem::transmute::<_, u32>(&function) will simply create a local variable that points to function and then get a reference to that variable. This will correspond to how this code works:

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

I don’t need to work with them in Rust, I need an address because I have an FFI that takes the address of the character in the current process

You can simply pass the as-is function to 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); } } 
+6
source

All Articles