如何在 Rust 的 FFI 中使用 C 预处理器宏? [英] How do I use C preprocessor macros with Rust's FFI?

查看:12
本文介绍了如何在 Rust 的 FFI 中使用 C 预处理器宏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些代码来连接用 C 编写的现有库.在我的 Rust 代码中,我希望能够使用来自 CPP 宏的值.如果我有一个如下所示的 C include.h:

I'm writing some code that interfaces an existing library written in C. In my Rust code I'd like to be able to use values from CPP macros. If I have a C include.h that looks like this:

#define INIT_FLAG 0x00000001

我希望能够像这样在 Rust 中使用它:

I'd like to be able to use it in Rust like this:

#[link(name="mylib")]
extern {
    pub static init_flag: c_int = INIT_FLAG;
}

我查看了其他 FFI 代码并且看到了很多人在 Rust 中复制这些值,而不是从 FFI 中获取它们.这似乎有点脆弱,我也希望能够处理通过 CPP 宏定义的更复杂的东西.只有在我确定我的 Rust 文件上运行 cpp 才会起作用CPP 宏只用于简单的事情.

I've looked at other FFI code and I see a lot of people duplicating these values in Rust instead of getting them from the FFI. This seems a little brittle, and I'd also like to be able to handle more complicated things that are defined via CPP macros. Running cpp over my Rust files would only work if I'm sure my CPP macros are only used for simple things.

推荐答案

这是不可能的,我觉得以后也不可能了.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.

这篇关于如何在 Rust 的 FFI 中使用 C 预处理器宏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆