gen_py3_reg.py 996 B

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