任何人都可以向我指出一些关于如何使用 Python(或 Perl 或任何其他 Linux 友好的脚本语言)编写脚本的文档,这些脚本从命令行从 XML 或 py 文件生成 C++ 代码。我希望能够编写一些 xml 文件,然后运行一个 shell 命令来读取这些文件并生成具有完全内联函数的 .h 文件,例如流式运算符、构造函数等。
最佳答案
如果您只想使用标准的 Python 内容来完成此操作,您可以尝试制作使用 Python 3 样式字符串格式的模板文件。例如,类模板可能如下所示:
{className}::{className}()
{{
}}
{className}::~{className}()
{{
}}
{className}::{className}(const {className}& other)
{{
}}
{className}& {className}::operator=(const {className}& other)
{{
return *this;
}}
那么你的 Python 代码就 super 简单了:
d = {}
d['className'] = 'MyCPlusPlusClassName'
with open(yourTemplateFile, 'r') as ftemp:
templateString = ftemp.read()
with open(generatedFile, 'w') as f:
f.write(templateString.format(**d))
当然,您可以使用相同的技巧在“className”旁边添加许多其他字段。如果您不需要条件代码生成之类的东西,您可以从这个简单的东西中获得很多好处。
关于使用 Python 生成 C++ 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2966618/