gen_py3_reg.py 952 B

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