我已经使用 rust-bindgen 生成了 rust 接口(interface)代码。
现在在 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 );
但是我得到一个错误:
error: mismatched types: expected
*const Struct_mps_key_s
, foundStruct_mps_key_s
(expected *-ptr, found enum Struct_mps_key_s)
我不是一个好的 C 程序员,我什至不明白这些 C static 甚至从哪里获取值。
感谢您的帮助。
编辑:
根据 Chris Morgan 的回答更新。
我添加了这段代码(注意,我用 mps_key_t 替换了 *const mps_key_s):
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;
使用rust :
pub type mps_key_t = *const Struct_mps_key_s;
这个接缝接缝比以前工作得更好,但现在我遇到了严重的崩溃:
error: internal compiler error: unexpected failure note: the compiler hit an unexpected failure path. this is a bug. note: we would appreciate a bug report: http://doc.rust-lang.org/complement-bugreport.html note: run with
RUST_BACKTRACE=1
for a backtrace task 'rustc' failed at 'expected item, found foreign item _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
最佳答案
#define MPS_KEY_ARGS_END <strong>(&</strong>_mps_key_ARGS_END<strong>)</strong>
&
部分表示它正在获取指向对象的指针,MPS_KEY_ARGS_END
的类型将为 mps_key_s const*
。在 Rust 中,它是 *const mps_key_s
(原始指针),可以用与 C 中相同的方式实现,&_mps_key_ARGS_END
。您可以像这样方便地定义 MPS_KEY_ARGS_END
:
static MPS_KEY_ARGS_END: *const mps_key_s = &_mps_key_ARGS_END;
关于c - Rust 调用 C,C 代码中的静态常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26580694/