首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用wasm-bindgen调用先前定义的任意javascript函数Rust?

如何使用wasm-bindgen调用先前定义的任意javascript函数Rust?
EN

Stack Overflow用户
提问于 2020-07-16 21:14:30
回答 1查看 359关注 0票数 2

在我的javascript中,在调用wasm之前,我定义了一个函数jalert,稍后我想使用wasm从Rust中调用它。我在wasm-bindgen的文档中找不到如何调用我之前在javascript中定义的任意函数,如下所示。我可以使用像alert和console.log这样的函数,因为它们已经是javascript的一部分,但是我不能让这个函数jalert工作。我在浏览器中得到一个错误,说它没有被定义。有了警报功能,它不会有任何问题。

代码语言:javascript
复制
    function jalert(sometext) {
        alert(sometext);
    }
    
    jalert("I am Claudio");
    
    // This works from Javascript

在Rust文件lib.rs

代码语言:javascript
复制
    #[wasm_bindgen]
    extern "C" {
        fn alert(s: &str);
        fn jalert(s: &str);
    }
    
    #[wasm_bindgen]
    pub fn run_alert(item: &str) {
        jalert(&format!("This is WASM calling javascript function jalert and {}", item));
        alert(&format!("This is WASM and {}", item));
    }
    
// The alert() code works fine. The jalert() call in run_alert() gives me a browser error that jalert is not defined
EN

回答 1

Stack Overflow用户

发布于 2020-07-16 22:19:49

我会说你需要将#wasm_bindgen添加到你的方法声明中:

代码语言:javascript
复制
#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(method, js_name = alert]
    fn alert(s: &str);
    #[wasm_bindgen(method, js_name = jalert]
    fn jalert(s: &str);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62935592

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档