Skip to content

Experience using wasm-bindgen from C #178

Closed
@jgravelle-google

Description

@jgravelle-google

Hello,

I did some experiments recently to see how well wasm-bindgen works for C code. I'm curious about host bindings support for C/C++, and was wondering about whether it makes sense to target wasm-bindgen for handling the polyfilling/bundling/etc part. Answer seems to be... maybe?

My approach

  1. Build a reference wasm_bindgen-using Rust module, targeting wasm, process with wasm-bindgen
  2. Build an equivalent C file, targeting wasm
  3. Disassemble the C-built .wasm, splice in the wasm_bindgen macro-generated imports and __wbindgen_describe functions, reassemble
  4. Concatenate a __wasm_bindgen_unstable custom section
  5. Run wasm-bindgen tool

Results

Technically this worked. I only tried passing strings and exporting structs so far. Some issues:

  • Passing &strs is nonobvious. I had to modify the C callsite to store strlen in __wbindgen_global_argument_ptr. Digging deeper this looks to be handled by the Into/FromWasmAbi traits, which I'm not sure how we'll implement in C. C++ can probably do some shenanigans with templates or class conversions here.
  • __wbindgen_global_argument_ptr is just kinda magic as far as I can tell.
  • __wbindgen_describe functions are going to be tricky to generate without toolchain magic.
  • This probably is more to do with my not knowing Rust very well, but passing structs by value in Rust works, whereas passing structs by value in C has a totally different ABI - the caller is responsible for allocating memory, not the callee. We can get a Rust-compatible ABI by restricting ourselves to passing C structs via pointer.

As is the name of the custom section, I'm well aware that the wasm-bindgen ABI is unstable :) . But I figure it's useful to bring this up now before the designs solidify with too many Rust-specific assumptions in place.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions