Is it possible to generate and execute Rust code a

2019-02-03 07:46发布

Using C, at runtime, I can:

  1. Create the source code of a function,
  2. Call out to gcc to compile it to a .so (Linux) (or use llvm, etc.),
  3. Load the .so, and
  4. Call the function.

Is a similar thing possible in Rust?

In particular I want to use Algebraic Data Types, so using a C subset of Rust's features is not sufficient.

1条回答
等我变得足够好
2楼-- · 2019-02-03 08:31

Not yet, officially, though it should be at least possible with not too much hacking. The biggest obstacle is that the libraries do not have any ability to do dynamic loading yet. Here's a potential strategy to make it work (on Rust's incoming branch).

  • Link to the rustc crate to drive the compiler programmatically. Be aware that the compiler is not threadsafe so only run one in-process build at a time.
  • Mark the function you want to call with #[no_mangle]. This should (I haven't tried it) produce an unmangled symbol name so it's easy to find.
  • Create minimal bindings to dlopen/dlsym
  • Find the function pointer and unsafely convert it to a Rust closure type (currently defined in sys::Closure).
  • Call the closure.

Rust also has a minimally-tested JIT that can be used for this type of thing, but it has some major bugs.

查看更多
登录 后发表回答