Last active
August 20, 2020 10:39
-
-
Save caiwan/f5a8601c648d49766fbf4a46c3aa430e to your computer and use it in GitHub Desktop.
Python C/C++ utils
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import json | |
import os | |
import sys | |
import pathlib | |
from hashlib import md5 | |
import tqdm | |
parser = argparse.ArgumentParser( | |
description="Packs binary files into const C arrays." | |
) | |
parser.add_argument("input", type=str, nargs="+", help="Asset descriptor file") | |
parser.add_argument( | |
"--out", | |
"-o", | |
dest="output", | |
type=str, | |
default="", | |
help="Output file base name (.c and .h will added).", | |
) | |
args = parser.parse_args() | |
def file_md5(file): | |
CHUNK_SIZE = 65536 | |
hasher = md5() | |
with open(file, "rb") as f: | |
while True: | |
data = f.read(CHUNK_SIZE) | |
hasher.update(data) | |
if not data: | |
break | |
return hasher.hexdigest() | |
def parseFile(filename): | |
with open(filename,"rb") as f: | |
out = "" | |
count = 0 | |
for r in f.read(): | |
s ='{0}, '.format(r) | |
# Put line break before if it | |
# would be longer than the limit | |
count += len(s) | |
if count >= 320: | |
s = "\n" + s | |
count = 0 | |
out += s | |
pass | |
pass | |
# cut the trailing comma and space | |
return out[:-2] | |
if __name__ == "__main__": | |
with open('{0}.h'.format(args.output),'w') as hf, open('{0}.c'.format(args.output), 'w') as cf: | |
hf.write("#pragma once \n\n") | |
hf.write("#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n") | |
output_name = os.path.basename(args.output) | |
for input_file in tqdm.tqdm (args.input): | |
if os.path.exists(input_file): | |
model={ | |
"filename": input_file, | |
"prefix": output_name, | |
"name": os.path.basename(input_file).lower().replace('.', '_').replace('-', '_'), | |
"size": os.stat(input_file).st_size | |
} | |
# h-file | |
hf.write("\t//{prefix}_{name} {filename}\n".format(**model)) | |
hf.write("\t#define SIZEOF_{prefix}_{name} {size}\n".format(**model)) | |
hf.write("\textern const unsigned char {prefix}_{name}[{size}];\n\n".format(**model)) | |
# c-file | |
cf.write("//{prefix}_{name} {filename}\n".format(**model)) | |
cf.write("const unsigned char {prefix}_{name}[{size}] = {{\n{data}\n}};\n\n".format(**model, data=parseFile(input_file))) | |
hf.write("#ifdef __cplusplus\n}\n#endif\n\n") | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment