gen_py_reg.py 888 B

12345678910111213141516171819202122232425262728293031323334
  1. from __future__ import print_function
  2. import sys
  3. template = '''
  4. extern "C" void PyImport_AppendInittab(const char* name, void (*fn)(void));
  5. extern "C" void {1}();
  6. namespace {
  7. struct TRegistrar {
  8. inline TRegistrar() {
  9. PyImport_AppendInittab("{0}", {1});
  10. }
  11. } REG;
  12. }
  13. '''
  14. def mangle(name):
  15. if '.' not in name:
  16. return name
  17. return ''.join('{}{}'.format(len(s), s) for s in name.split('.'))
  18. if __name__ == '__main__':
  19. if len(sys.argv) != 3:
  20. print('Usage: <path/to/gen_py_reg.py> <python_module_name> <output_file>', file=sys.stderr)
  21. print('Passed: ' + ' '.join(sys.argv), file=sys.stderr)
  22. sys.exit(1)
  23. with open(sys.argv[2], 'w') as f:
  24. modname = sys.argv[1]
  25. initname = 'init' + mangle(modname)
  26. code = template.replace('{0}', modname).replace('{1}', initname)
  27. f.write(code)