且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Rust 的 FFI 中使用 C 预处理器宏?

更新时间:2023-10-06 14:13:34

这是不可能的,我觉得以后也不可能了.C 宏给它们带来了太多的问题.如果你想在你的 Rust 源代码上运行 cpp,你可以手动完成.

It is impossible, and I don't think it will be possible in the future. C macros bring too many problems with them. If you want to run cpp over your Rust sources, you can do it manually.

如果您不想这样做,并且如果有很多常量,并且您也不想将它们的值从 C 代码复制到 Rust,您可以创建一个 C 包装器,它将为全局变量提供这些值:

If you don't want to do it and if there is a lot of constants and you also don't want to copy their values from C code to Rust you can make a C wrapper which will provide global variables with these values:

#define INIT_FLAG 0x00000001

...

const int init_flag = INIT_FLAG;

你编译这个文件,从中创建一个静态库并像往常一样链接到它:

You compile this file, create a static library from it and link to it as usual:

$ gcc -c init_flag.c
$ ar r libinitflag.a init_flag.o

锈源:

use std::libc;

#[link(name="initflag", kind="static")]
extern {
    pub static init_flag: libc::c_int;
}

Rust 源几乎与您尝试实现的目标相同.但是,您将需要 C 粘合对象文件.

Rust source is nearly identical to what you tried to achieve. You will need C glue object file, however.