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

查看:134
本文介绍了如何在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;
}

锈源与您尝试实现的源几乎相同.但是,您将需要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天全站免登陆