如何将宏属性应用于单独模块中定义的函数? [英] How do I apply a macro attribute to a function defined in a separate module?

查看:48
本文介绍了如何将宏属性应用于单独模块中定义的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣通过 rust-webpack-template 使用 wasm-bindgen 将 Rust 代码编译为 WebAssembly.但是,我想避免直接用 #[wasm_bindgen] 属性宏直接包装我的代码,以便我可以从生成的 WebAssembly 接口中分离出函数逻辑,以便更好地组织我的项目.相反,我更愿意将绑定生成放在一个单独的文件中,例如:

I'm interested in using wasm-bindgen via rust-webpack-template to compile Rust code to WebAssembly. However, I'd like to avoid directly wrapping my code with the #[wasm_bindgen] attribute macro directly so that I can separate out the function logic from the generated WebAssembly interface to better organize my project. Instead, I would prefer to have binding generation be in a separate file, for example:

mod my_code;
use my_code::my_function;

#[wasm_bindgen]
my_function; // I want to do something like this!

我知道 #[wasm_bindgen] 是一个宏属性,它在通常遵循的函数定义的 AST 上运行,但是有没有一种方法可以将该宏应用于其他地方定义的代码?>

I understand that #[wasm_bindgen] is a macro attribute that operates on the AST of the function definition that usually follows, but is there an approach for applying that macro to code defined elsewhere?

推荐答案

据我所知,没有办法做到这一点.宏对它们所附加的代码的 AST 进行操作,这里没有要附加的代码.

As far as I know, there's no way to do this. Macros operate on the AST of the code they are attached to, and there's no code to be attached to here.

如果你真的需要这个,你必须复制并粘贴你的函数的签名:

If you really need this, you'll have to copy-and-paste the signature of your function:

mod my_code {
    pub fn my_function(_: i32) -> String {
        unimplemented!()
    }
}

#[wasm_bindgen]
fn my_function(a: i32) -> String {
    my_code::my_function(a)
}

您可以编写一个宏来使包装稍微不那么乏味,但您仍然需要复制函数名称、参数类型和返回类型.

It's possible you could write a macro to make the wrapping slightly less tedious, but you'll still need to replicate the function name, argument types, and return type.

这篇关于如何将宏属性应用于单独模块中定义的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆