如何在Rust FFI中访问C全局变量/常量? [英] How can I access a C global variable/constant in Rust FFI?
问题描述
我需要访问Rust中从C导出的常量值.
I need to access a value of a constant exported from C in Rust.
我想从实际符号中读取值,而不仅仅是将值复制并粘贴到Rust(在我的情况下,该值是一个指针,而C检查指针是否相等).
I want to read the value from the actual symbol, and not just copy'n'paste the value to Rust (in my case the value is a pointer, and C checks for pointer equality).
extern void *magic;
要使魔术:* const c_void
在Rust中可读的语法是什么?
What's the syntax to get magic: *const c_void
readable in Rust?
推荐答案
use std::os::raw::c_void;
extern "C" {
#[no_mangle]
static magic: *const c_void;
}
可选地,在 extern
之前可以有#[link(kind ="static",name =< c库名称"))]
获取实际链接的符号.
Optionally, before the extern
there can be #[link(kind="static", name="<c library name>")]
to get the symbol actually linked.
即使是常量,也可以使用 static
声明外部可链接项,而不仅仅是 const
关键字(否则,您将获得外部项不能为 const
").
Externally linkable items, even if constant, need be declared with static
, not just const
keyword (otherwise you get "extern items cannot be const
").
这篇关于如何在Rust FFI中访问C全局变量/常量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!