Skip to content

Instantly share code, notes, and snippets.

@7shi
Created October 8, 2011 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 7shi/1273073 to your computer and use it in GitHub Desktop.
Save 7shi/1273073 to your computer and use it in GitHub Desktop.
クロージャをサンクで包む
#include <functional>
#include <stdio.h>
#include "xbyak/xbyak.h"
template <class T>
struct Thunk : public Xbyak::CodeGenerator {
Thunk(T *f) {
mov(ecx, reinterpret_cast<intptr_t>(f));
auto p = &T::operator();
jmp(*reinterpret_cast<void **>(&p));
}
void(*getPtr())() {
return reinterpret_cast<void(*)()>(
const_cast<Xbyak::uint8 *>(getCode()));
}
};
void call(void(*f)()) { f(); }
int main() {
int a = 1;
auto f = [&] { printf("%d\n", a++); };
f();
f();
Thunk<decltype(f)> thunk(&f);
auto f2 = thunk.getPtr();
f2();
call(f2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment