【问题标题】:Rust calling C, static const in C codeRust 调用 C,C 代码中的静态 const
【发布时间】:2014-10-27 03:14:31
【问题描述】:

我已经使用 rust-bindgen 生成了 rust 接口代码。

现在你可以在 C 代码中找到:

extern const struct mps_key_s _mps_key_ARGS_END;
#define MPS_KEY_ARGS_END (&_mps_key_ARGS_END)

请注意,代码_mps_key_ARGS_END 的其余部分不会再次出现。

宏 MPS_KEY_ARGS_END 经常在其他类似 mps_key_s 中使用。

现在 rust-bindgen 生成的代码是这样的:

pub static _mps_key_ARGS_END: Struct_mps_key_s;

现在在 C 代码中是一个示例用法:

extern void _mps_args_set_key(mps_arg_s args[MPS_ARGS_MAX], unsigned i,
                              mps_key_t key);

_mps_args_set_key(args, 0, MPS_KEY_ARGS_END);

在 rust 中看起来像这样:

pub fn _mps_args_set_key(args: [mps_arg_s, ..32u], i: ::libc::c_uint,
                         key: mps_key_t);

现在我试着这样称呼它:

_mps_args_set_key(args, 0 as u32, _mps_key_ARGS_END );

但我得到一个错误:

错误:不匹配的类型:预期 *const Struct_mps_key_s,找到 Struct_mps_key_s(预期 *-ptr,找到枚举 Struct_mps_key_s)

我不是一个优秀的 C 程序员,我什至不明白这些 C 静态甚至从哪里获得值。

感谢您的帮助。

编辑:

根据 Chris Morgan 的回答进行更新。

我添加了这段代码(注意,我将 *const mps_key_s 替换为 mps_key_t):

pub static MPS_KEY_ARGS_END: mps_key_t = &_mps_key_ARGS_END;

只是为了获得一些关于我为什么在 C 中使用 mps_key_t 的额外信息:

typedef const struct mps_key_s *mps_key_t;

生锈了:

pub type mps_key_t = *const Struct_mps_key_s;

这个接缝比以前工作得更好,但现在我遇到了严重的崩溃:

错误:内部编译器错误:意外失败注意:编译器 遇到意外的失败路径。这是一个错误。注意:我们会 感谢错误报告: http://doc.rust-lang.org/complement-bugreport.html 注意:运行 RUST_BACKTRACE=1 的回溯任务“rustc”在“预期”失败 项目,发现外国项目 _mps_key_ARGS_END::_mps_key_ARGS_END (id=1102)', /home/rustbuild/src/rust-buildbot/slave/nightly-linux/build/src/libsyntax/ast_map/mod.rs:327

【问题讨论】:

标签: c rust bindgen


【解决方案1】:
#define MPS_KEY_ARGS_END <strong>(&amp;</strong>_mps_key_ARGS_END<strong>)</strong>

&amp; 部分表示它正在获取指向对象的指针,MPS_KEY_ARGS_END 的类型将是 mps_key_s const*。在 Rust 中,这是 *const mps_key_s(一个原始指针),并且可以通过与 C 中相同的方式实现,&amp;_mps_key_ARGS_END。您可以像这样方便地定义MPS_KEY_ARGS_END

static MPS_KEY_ARGS_END: *const mps_key_s = &_mps_key_ARGS_END;

【讨论】:

  • @MatthieuM.: 好点(我不习惯在 C 中工作并忘记了这一点)。已修改。
猜你喜欢
  • 2020-08-01
  • 2015-06-07
  • 2012-07-05
  • 2020-09-26
  • 2010-12-21
  • 2014-01-24
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
相关资源
最近更新 更多