3

I have a WASM function that I want to use in my near-sdk Rust project that targets WASM. How can I call this function inside my Rust code?

eduardogbg
  • 553
  • 4
  • 18
  • Where are you intending to run it? The WASM module has to be loaded somewhere. – PitaJ Aug 30 '22 at 20:38
  • I'm using near-sdk, which uses WASM as a portable assembler format. I expected that I could use some sort of FFI, considering that I'm going to compile to WASM anyways. I would like to avoid interpreting it in runtime if possible. – eduardogbg Aug 31 '22 at 20:41

1 Answers1

3

You haven't really told enough about your situation to give a detailed answer. (Where does that WASM function come from? What environment are you using, if not JS?) But I can tell you the general three approaches you have:

  1. Use a WASM interpreter that can run anywhere including on WASM, like wasm3, to execute the "function" from your "Rust project". This will be slow.
  2. Give your "Rust project" an imported function that instructs whatever engine is running that to run some other WASM module held in the "Rust project"s memory. This can be done, JS or not, but you'd need to be in control of the execution engine
  3. Link the two wasm modules into one: "function" WASM file could essentially be a static library, and you can link it like one. However, this requires that the "function" WASM file was produced with this in mind, it must have the necessary linking custom section. (You can't just smack two normal WASM files together, they wouldn't know how to coordinate static memory use, e.g.)
Caesar
  • 6,733
  • 4
  • 38
  • 44
  • I see. That binary is being generated by a compiler I have little knowledge about, but I could try tweaking it so solution 3 could be possible. Supposing I managed to do it, could you direct me to some material about linking WASM and how to declare this FFI in my Rust code? – eduardogbg Aug 31 '22 at 20:45
  • 1
    @eduardogbg Would [this](https://stackoverflow.com/questions/73604042/compiling-rust-that-calls-c-to-wasm) serve as an example? – Caesar Sep 05 '22 at 12:13