代码之家  ›  专栏  ›  技术社区  ›  Petok Lorand

将字符缓冲区转换为函数指针

  •  -1
  • Petok Lorand  · 技术社区  · 6 年前

    int main(void)
    {
        char buffer[] = "\xB8\x04\x00\x00\x00\xC3";
        auto func = (int(*)())buffer;
        func();
    
        return 0;
    }
    

    现在,如果我不想在运行时为函数调用付费,换句话说,我想将缓冲区视为 inline 功能。

    我第一次天真的尝试就是宣布 buffer func 作为 constexpr 把c型铸件换成 static_cast ,尽管这似乎不起作用,因为根据gcc,这是一个无效的强制转换。 reinterpret_cast 当然,但显然不能在编译时计算

    1 回复  |  直到 6 年前
        1
  •  2
  •   n. m. could be an AI    6 年前

    内联汇编代码可以在C++函数中注入 asm declaration . 此构造是有条件支持和定义实现的。

    下面是一个使用 asm 在x86上用GCC构造声明。

    #include <iostream>
    
    template <int nontype>
    int add(int operand)
    {
        int sum;
    
        asm ("movl %1, %0\n\t"
             "addl %2, %0"
             : "=r" (sum)
             : "r" (operand), "r" (nontype)
             : "0");
    
        return sum;
    }
    
    int main()
    {
        std::cout << add<42>(6) << "\n";
    }
    

    按预期打印48张。

    注意gcc的 asm公司