jittest.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include "asmjit/src/asmjit/asmjit.h"
  2. using namespace asmjit;
  3. // Signature of the generated function.
  4. typedef int (*Func)(void);
  5. int value()
  6. {
  7. return 42;
  8. }
  9. int main(int argc, char* argv[]) {
  10. JitRuntime rt; // Runtime specialized for JIT code execution.
  11. CodeHolder code; // Holds code and relocation information.
  12. code.init(rt.getCodeInfo()); // Initialize to the same arch as JIT runtime.
  13. X86Assembler a(&code); // Create and attach X86Assembler to `code`.
  14. a.mov(x86::eax, 1); // Move one to 'eax' register.
  15. a.call(reinterpret_cast<uint64_t> (&value));
  16. a.ret(); // Return from function.
  17. // ----> X86Assembler is no longer needed from here and can be destroyed <----
  18. Func fn;
  19. Error err = rt.add(&fn, &code); // Add the generated code to the runtime.
  20. if (err) return 1; // Handle a possible error returned by AsmJit.
  21. // ----> CodeHolder is no longer needed from here and can be destroyed <----
  22. int result = fn(); // Execute the generated code.
  23. printf("%d\n", result); // Print the resulting "1".
  24. // All classes use RAII, all resources will be released before `main()` returns,
  25. // the generated function can be, however, released explicitly if you intend to
  26. // reuse or keep the runtime alive, which you should in a production-ready code.
  27. rt.release(fn);
  28. return 0;
  29. }