小编Nik*_*ock的帖子

从内存中执行代码

假设我想在C中进行JIT编译.我反汇编函数并将其代码插入到我的程序中的内存中:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>


void* alloc_executable_memory(size_t size) {

  void *ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);

  if (ptr == MAP_FAILED) {
      fprintf(stderr, "%s\n", "mmap failed");
      return NULL;
  }

  return ptr;
}

void push_code_into_memory(unsigned char *memory) {
  unsigned char code[] = {
    0x48, 0x89, 0xf8,       // mov %rdi, %rax
    0,48, 0x83, 0xc0, 0x04, // add $4, %rax
    0xc3                    // ret
  };

  memcpy(memory, code, sizeof(code));
}

int make_memory_executable(void* memory, size_t size) { …
Run Code Online (Sandbox Code Playgroud)

c memory jit

2
推荐指数
1
解决办法
163
查看次数

根据参数计数推导可变参数模板

想象一下我有两个功能:

void string(const char *str)
{
    std::cout << "this is string" << std::endl;
}

void number(const char *str, double f)
{
    std::cout << "this is number" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我想编写一个通用包装器,以便能够format()像这样调用:

int main() {
    format("single arg");
    format("format string", 1.0);
    format("single arg", "format string", 1.0);
    format("format string 1", 1.0, "just string arg", "format string 2", 2.0);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

也就是说,如果参数以 {string, number} 对的形式出现,则调用number(); 否则请致电string(). 显然,只能从右到左解包参数。我尝试按照以下(错误)方式实现它:

template<class T>
void operation(T first)
{
    string(first);
}

template<class T, class …
Run Code Online (Sandbox Code Playgroud)

c++ templates metaprogramming variadic-templates

1
推荐指数
1
解决办法
74
查看次数

标签 统计

c ×1

c++ ×1

jit ×1

memory ×1

metaprogramming ×1

templates ×1

variadic-templates ×1