[英]How to place a C struct on the function stack in Rust?
I would like to transfer the following C code我想转以下C代码
HMAC_CTX context;
HMAC_CTX_init(&context);
into Rust.进入 Rust。 But while it's easy to define an extern function, it seems impossible to directly use a C struct in Rust.
但是,虽然定义外部 function 很容易,但在 Rust 中直接使用 C 结构似乎是不可能的。
extern "C" {
use HMAC_CTX; // does not work!
fn HMAC_CTX_init(ctx: *mut HMAC_CTX);
}
I know that I could define a placeholder struct in Rust我知道我可以在 Rust 中定义一个占位符结构
struct HMAC_CTX;
...but an instance of may not hold enough space for the real C struct. ...但是一个实例可能没有足够的空间容纳真正的 C 结构。
let mut ctx = HMAC_CTX;
unsafe { HMAC_CTX_init(&mut ctx); }
Is there a way of solving this without redefining the whole struct in Rust?有没有办法在不重新定义 Rust 中的整个结构的情况下解决这个问题? That would create a dependency from the external code to my Rust project and I would like to avoid this.
这将创建从外部代码到我的 Rust 项目的依赖关系,我想避免这种情况。
Use rust-bindgen
to generate Rust bindings.使用
rust-bindgen
生成 Rust 绑定。 It'll generate a rust version of the corresponding C struct and keep it synchronized if placed in the build-script.如果放置在构建脚本中,它将生成相应 C 结构的 rust 版本并保持同步。
Adds complexity to the build process and adds a dependency.增加了构建过程的复杂性并增加了依赖。
Create a Rust version of the C struct by hand.手动创建 C 结构的 Rust 版本。
#[repr(C)]
pub struct HMAC_CTX {
md: *mut EVP_MD,
md_ctx: EVP_MD_CTX,
i_ctx: EVP_MD_CTX,
o_ctx: EVP_MD_CTX,
key_length: c_uint,
key: [c_uchar; 128],
}
This requires to follow changes of the C code and manually update the Rust struct.这需要遵循 C 代码的更改并手动更新 Rust 结构。 Also further structs might have to be defined.
还可能需要定义进一步的结构。 Add a dependency to the internals of the called library:-(
向被调用库的内部添加依赖项:-(
Create a placeholder struct.创建一个占位符结构。
pub struct HMAC_CTX {
_placeholder: [c_uchar; 256],
}
This struct needs to be large enough to hold all the internals of the C struct.该结构需要足够大以容纳 C 结构的所有内部结构。 Indirect dependency:-( If the C struct size exceeds the placeholder size, it could lead to unsafe behavior.
间接依赖:-( 如果 C 结构大小超过占位符大小,则可能导致不安全行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.