如何在 Rust FFI 中访问 C 全局变量/常量?

问题描述 投票:0回答:1

我需要访问 Rust 中从 C 导出的常量值。

我想从实际符号中读取值,而不仅仅是将值复制粘贴到 Rust(在我的例子中,该值是一个指针,C 检查指针是否相等)。

extern void *magic;

在 Rust 中让

magic: *const c_void
可读的语法是什么?

c rust ffi
1个回答
18
投票
use std::os::raw::c_void;

extern "C" {
    static magic: *const c_void;
}

可选地,在

extern
之前可以有
#[link(kind="static", name="<c library name>")]
来获取实际链接的符号。

外部可链接项,即使是常量,也需要使用

static
进行声明,而不仅仅是
const
关键字(否则您会得到“外部项不能是
const
”)。

© www.soinside.com 2019 - 2024. All rights reserved.