[英]How do I obtain the address of a function?
How do I obtain a function address in Rust?如何在Rust中获取function地址? What does '&somefunction' exactly mean?
“&somefunction”到底是什么意思?
What addresses do I get doing我要做什么地址
std::mem::transmute::<_, u32>(function)
or或者
std::mem::transmute::<_, u32>(&function)
(on 32-bit system, of course)? (当然是在 32 位系统上)?
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. 我对此不太确定,但我认为
std::mem::transmute::<_, u32>(&function)
只会创建一个指向function
的局部变量,然后获取对该变量的引用。 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
我不需要在Rust中使用它们,我需要一个地址因为我有一些FFI在当前进程中获取符号的地址
You can still just pass the function as-is to the extern functions that will use the callback: 您仍然可以将函数原样传递给将使用回调的extern函数:
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). @Shepmaster 的回答给出了这个问题的答案(虽然也给出了其他不相关但可能对某些人有用的信息)。 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引用 function 似乎创建了一个局部变量,就像 with
let a = &42;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.