Let me explain a trick. Jinja2 is a template script that can generate text from templates. What you need to do is write your C code template main.c.j2:
#include <stdio.h>
int main()
{
printf("hello {{name}}.\n");
return 0;
}
then you can transform it into C code with the trans.py:
import os
from jinja2 import PackageLoader, Environment, FileSystemLoader
TemplateLoader = FileSystemLoader(os.path.abspath("."))
env = Environment(loader = TemplateLoader)
template = env.get_template("main.c.j2")
print(template.render(name = "Jack"))
run python trans.py and you will see this C code on screen:
#include <stdio.h>
int main()
{
printf("hello Jack.\n");
return 0;
}
That's real C code, {{name}} is replaced into Jack. See the Jinja2 doc for more interesting features.
Answer from alven darthy on Stack Overflowpython - Generating C code from script: how to template? - Stack Overflow
How to generate C code from Python? - Stack Overflow
C++ code generation with Python - Stack Overflow
syntax - How to generate C++ code? (probably WITH (not FROM) Python) - Software Engineering Stack Exchange
Videos
Is anybody aware of any Python library capable of taking a string of simple Python code (e.g. only with if clauses, for loops and math ops, and just manipulating arrays) into a corresponding snippet of C code?
Nuitka is sort of that, but it still links against CPython to provide object semantics and such. What's your end goal here?
Yeah, numba! As long as you keep your python code to the features supported by numba (check by using nopython=True) it will speed things up immensely.
Let me explain a trick. Jinja2 is a template script that can generate text from templates. What you need to do is write your C code template main.c.j2:
#include <stdio.h>
int main()
{
printf("hello {{name}}.\n");
return 0;
}
then you can transform it into C code with the trans.py:
import os
from jinja2 import PackageLoader, Environment, FileSystemLoader
TemplateLoader = FileSystemLoader(os.path.abspath("."))
env = Environment(loader = TemplateLoader)
template = env.get_template("main.c.j2")
print(template.render(name = "Jack"))
run python trans.py and you will see this C code on screen:
#include <stdio.h>
int main()
{
printf("hello Jack.\n");
return 0;
}
That's real C code, {{name}} is replaced into Jack. See the Jinja2 doc for more interesting features.
This could be done with the re library in Python.
Search for the blockname and replace it with the new block:
re.sub(f"// start generated block \({blockname}\).*// end generated block \({blockname}\)", new_code, fileContents, flags=re.DOTALL)
If you want to do this simply with just standard Python stuff you might try making template files that use the Python 3 style string formatting. For example, a class template might look something like this:
{className}::{className}()
{{
}}
{className}::~{className}()
{{
}}
{className}::{className}(const {className}& other)
{{
}}
{className}& {className}::operator=(const {className}& other)
{{
return *this;
}}
Then your Python code is super simple:
d = {}
d['className'] = 'MyCPlusPlusClassName'
with open(yourTemplateFile, 'r') as ftemp:
templateString = ftemp.read()
with open(generatedFile, 'w') as f:
f.write(templateString.format(**d))
Of course you can add lots of other fields alongside 'className' using the same trick. If you don't need stuff like conditional code generation you can get a lot of mileage out of something this simple.
I'm afraid you will not find an already-built in solution that takes your particular xml or python files and transforms them onto your required output "out of the box".
You will have to implement the parsing, the data treatment and output yourself. Not all by yourself, though; here are some pointers regarding the parsing and output.
Python comes with 2 different XML parsers (SAX and DOM -scroll down to see some examples). You will have to use one of them in order to read the source files.
For generating the output more easily, you can probably use a templating library, such as StringTemplate, or just generate the code manually, if it's small.
So you want to translate some (yours) domain specific language (DSL) to some flavor of C++. I am doing exactly the same in my GCC MELT implementation (inactive as of 2017). It is a Lisp-y domain specific language to customize the GCC compiler. See also this answer giving slightly more details, and this one giving relevant references.
Here are some advice; I cannot be more specific because I have absolutely no idea what your domain specific language is for. Is it Turing-complete (perhaps accidentally)? Probably yes! Read also this draft report.
if you never studied it, study compiler techniques (including lexing & parsing). They are highly relevant.
read Scott's book Programming Language Pragmatics (at least for inspiration).
consider (instead of developing your own DSL) embedding some existing interpreter, perhaps Guile or Lua. It might be considerably simpler.
be aware that designing and implementing a passable DSL which is compiled (perhaps to C++) is a lot of work (years!). Read the mythical man month, Hofstadter's law, etc... Perhaps you want (or not) to bootstrap your language implementation...
if your DSL is somehow useful (e.g. you are not the only one writing scripts in it), be aware that eventually some crazy user would code large scripts (many thousands lines) in it. So design the language seriously!
first, you need a well defined (in your head!) representation of the abstract syntax tree (which might not be a tree, but a graph) of the generated C++ code and you should build (in memory) the AST before emitting the corresponding C++ code
you might want to emit
#linedirectives (referring to positions inside your DSL scripts). It is very useful (for debugging) but emitting them is quite hard.you might need several other internal representations, between the DSL source and the generated C++ code, and your C++ code generator (actually a specialized compiler) is transforming some representations into another ones, and finally into an AST which is emitted as C++ code.
you should care about the memory model; so read about garbage collection techniques (at the very least, for terminology and concepts), see the GC handbook. You probably don't want a stupid user script to crash the computer or the process. So you need to handle memory (& memory leaks).
perhaps you might consider, instead of generating C++ code, to use JIT compiling techniques: GCCJIT, LLVM, libjit, asmjit, ...
perhaps SciLab, R, Octave, Julia might be relevant for your work (because they might avoid you to start your own DSL)
On Linux specifically, you might generate C++ code in some temporary file, compile it into a plugin (read Drepper's paper How To Write Shared Libraries and about Invoking GCC and see elf(5)) , then dlopen(3) it (and use dlsym(3) to get function pointers). Read then the C++ dlopen mini-howto. The RefPerSys project is doing that.
The CLASP project should be relevant: it is about Common Lisp and molecular chemistry simulation.
Do you need to generate C++, or compiled code? You can leverage LLVM to produce compiled output from scripted tooling. The clang intermediate language is verbose but powerful - its what C++ code (or any other supported language) gets parsed into before compilation. Alternatively you can generate C++ from tools that still leverage the Clang parser, so instead of manipulating the text, you manipulate the internal AST the parser holds.
For an example, look at cmonster, which is a (rudimentary) python wrapper for clang's C++ parser.
Are there any libraries that can easily convert Python to C/C#/or C++? Ones where a person doesn't have to "calibrate" it, just, pip install library and then they can have their Python code in C,C#,or C++?