Alternative to ctor/inventory for when compiling to wasm?

Viewed 273

The ctor crate doesn't support web assembly currently, although there is active discussion about how to fix this.

Although I am well aware of the issues associated with static initialization coming from C++, being able to register things with a factory at startup is a very handy capability, and is necessary to avoid violating the DRY principle in a lot of cases. Without it every time you want to add a new possibility to your factory you have to add a separate line of code to main(), possibly more lines if you need to import your new function. This quickly gets tedious.

I am wondering if it is possible to build something equivalent (at least when everything you want to register is concentrated inside a single crate) using a procedural attribute macro and build.rs. The macro would be used to mark the functions that I want to register, and it's implementation would save the module paths ("crate::your::registered_function") of those functions off to the side somewhere in a file but otherwise just be a passthrough. Then build.rs would generate a function that calls all the functions listed in the file, and I would have main() call that one function by hand.

  • Is there a different trick that would work instead?
  • Does an implementation of this already exist somewhere I could use as a reference?
  • How would the procedural macro actually generate the module path for the function to be called? There is module_path! but if invoked from inside the definition of the procedural macro it will give the module path for the macro, not the module path associated with what the TokenStream is going to expand into. The macro could generate a call to module_path! but that won't evaluate until later when the final program is run.
0 Answers
Related