gpt4 book ai didi

c++ - 将函数内容打印为字符串,但也可以将其作为代码运行

转载 作者:行者123 更新时间:2023-12-03 23:38:19 24 4
gpt4 key购买 nike

我想制作一个可以在不破坏复制函数功能的情况下打印另一个函数内容的函数。
例如:

int functionToCopy()
{
int a{ 5 };
int b{ 6 };

return a + b;
}

void printCopiedFunction()
{
some magical code to print the contents of the first function;
}

int main()
{
std::cout << functionToCopy() << '\n';
std::cout << printCopiedFunction() << '\n';

return 0;
}
输出:
11

int functionToCopy()
{
int a{ 5 };
int b{ 6 };

return a + b;
}
我只是一个初学者,C++ 是我的第一门语言。我已经做了很多搜索和思考,但我能想到的唯一方法就是从字面上复制函数并将第二个函数设为字符串,这会使我的代码翻倍,我宁愿避免这种情况。我想要执行此操作的程序目前有 26 个需要像这样复制的函数,因此可以重用单个函数将是首选。
std::string copiedFunction()
{
std::string str{ R"(
int functionToCopy()
{
int a { 5 };
inb b { 6 };

return a + b;
})"
};
return str;
}
任何帮助深表感谢!这是我唯一一次在论坛上寻求这样的帮助,但我认为目前这超出了我的能力范围。我知道这可能是不可能的,或者它可能非常复杂并且目前超出了我的范围。先感谢您!

最佳答案

C++ 没有 reflection所以你不能单独使用语言直接做到这一点。但是你可以通过将函数移动到头文件中来实现,#include在 .cpp 文件中添加该文件,并将头文件构建到目标文件中,使其内容可作为常量字符串使用。
首先,把这个放在foo.h :

inline int functionToCopy()
{
int a{ 5 };
int b{ 6 };

return a + b;
}
然后,使用来自 https://stackoverflow.com/a/46221837/4323 的信息使用 objcopy创建目标文件:
objcopy --input binary --output elf64-x86-64 foo.h foo.o
然后像这样更改主文件:
#include <iostream>
#include <string_view>
#include "foo.h"

extern "C" const char* _binary_foo_h_start; // defined in foo.o
extern "C" const char* _binary_foo_h_size;

std::string_view printCopiedFunction()
{
return {_binary_foo_h_start, _binary_foo_h_size};
}

int main()
{
std::cout << functionToCopy() << '\n';
std::cout << printCopiedFunction() << '\n';
}
和链接 foo.o在构建时进入您的可执行文件。
请注意 objcopy在 Linux 和其他一些系统上可用,您可能需要在您的平台上寻找等价物。例如,如果您有 xxd : https://stackoverflow.com/a/411000/4323
在 Windows 上,您可以将文本文件(即头文件)作为“资源”嵌入到可执行文件中,并在运行时加载资源,如下所示: Embed Text File in a Resource in a native Windows Application

关于c++ - 将函数内容打印为字符串,但也可以将其作为代码运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68044785/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com