gpt4 book ai didi

binding - 如何自动重写 bindgen 创建的 FFI 函数的签名?

转载 作者:行者123 更新时间:2023-11-29 08:17:47 25 4
gpt4 key购买 nike

我在 rust-bindgen 的帮助下为 C 库编写绑定(bind),函数签名自动生成到 bindings.rs 中,如下所示:

#[repr(C)]
struct A {
//...
}

struct B {
//...
}

extern "C" {
pub fn foo(x: *mut A, y: *mut B);
//...
}

我对 foo 的签名不是很满意,因为我知道 x 是一个指向常量结构的指针。另外,我想申请this idea将此签名改进为类似

extern "C" {
pub fn foo(x: &'_ A, y: &'_ mut B);
}

但是 binding.rs 有一堆函数,比如 foo ,手动重写它们是一项非常耗时的任务,我认为宏(或其他东西)应该有所帮助.例如,可能存在一个(或多个)魔法宏 rewrite!


// hide
mod ffi {
include!("binding.rs"); // so bunch of functions: foo, bar
}

// re-exports
extern "C" {
rewrite!(foo); // should expand to: pub fn foo(x: &'_A, y: &'_ mut B)
rewrite!(bar);
}

我正处于这项工作的早期阶段。我什至不知道这样的问题是否可以通过宏或其他任何方式解决,所以我正在寻找任何切入点。

我已经 cross-posted this question到 Rust 用户论坛。

最佳答案

声明式宏无法完成此操作,但过程式宏可能可以。用 proc_macro2 ,您可以通过在其上放置重写属性来修改函数声明的 token 流,例如

extern "C" {
#[rustify]
pub fn foo(x: *mut A, y: *mut B);
}

还有你的rustify宏将替代 *mut TypenameOption<&mut Typename> .

我不知道你会如何改变 mut借用而不用 *const 替换原始声明.

关于binding - 如何自动重写 bindgen 创建的 FFI 函数的签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56786346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com