gen_py_reg.py 844 B

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