使用 Python 生成 C++ 代码

标签 c++ python code-generation

任何人都可以向我指出一些关于如何使用 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/

相关文章:

python - 使用 NCBIXML 仅解析来自 BLAST 输出的前 3 个命中

python - 在目录中查找未使用的 python 模块

Python feedparser 不返回任何条目

java - 对象相识

c++ - 什么是 diff b/w Includes in VC++ Directories options 和 Additional include directories in C++ -> General in Visual Studio

c++ - 为什么一个非常量静态成员会有多个定义?

java - 从非java文件编译java类

c++ - 计算使用长度为 1,2,3,4,......m 的步长到达第 N 步的方法数。(其中 m<=n)

php - 功能与重复代码

java - 当表具有外键时 Telosys 代码生成失败