prebuild.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import os
  2. def generate_python_sources():
  3. sources = {}
  4. for file in sorted(os.listdir("python")):
  5. if not file.endswith(".py"):
  6. continue
  7. key = file.split(".")[0]
  8. const_char_array = []
  9. with open("python/" + file) as f:
  10. # convert to char array (signed)
  11. for c in f.read().encode('utf-8'):
  12. if c < 128:
  13. const_char_array.append(str(c))
  14. else:
  15. const_char_array.append(str(c - 256))
  16. const_char_array.append('0')
  17. const_char_array = ','.join(const_char_array)
  18. sources[key] = '(const char[]){' + const_char_array + '}'
  19. header = '''#pragma once
  20. // generated by prebuild.py
  21. #include <map>
  22. #include <string>
  23. namespace pkpy{
  24. inline std::map<std::string, const char*> kPythonLibs = {
  25. '''
  26. for key, value in sources.items():
  27. header += f' {{ "{key}", {value} }},\n'
  28. header += ''' };
  29. } // namespace pkpy
  30. '''
  31. return header
  32. # use LF line endings instead of CRLF
  33. with open("include/pocketpy/_generated.h", "wt", encoding='utf-8', newline='\n') as f:
  34. f.write(generate_python_sources())