makegw.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. """Utility functions for writing out gateway C++ files
  2. This module will generate a C++/Python binding for a specific COM
  3. interface.
  4. At this stage, no command line interface exists. You must start Python,
  5. import this module, change to the directory where the generated code should
  6. be written, and run the public function.
  7. This module is capable of generating both 'Interfaces' (ie, Python
  8. client side support for the interface) and 'Gateways' (ie, Python
  9. server side support for the interface). Many COM interfaces are useful
  10. both as Client and Server. Other interfaces, however, really only make
  11. sense to implement one side or the other. For example, it would be pointless
  12. for Python to implement Server side for 'IRunningObjectTable', unless we were
  13. implementing core COM for an operating system in Python (hey - now there's an idea!)
  14. Most COM interface code is totally boiler-plate - it consists of
  15. converting arguments, dispatching the call to Python, and processing
  16. any result values.
  17. This module automates the generation of such code. It has the ability to
  18. parse a .H file generated by the MIDL tool (ie, almost all COM .h files)
  19. and build almost totally complete C++ code.
  20. The module understands some of the well known data types, and how to
  21. convert them. There are only a couple of places where hand-editing is
  22. necessary, as detailed below:
  23. unsupported types -- If a type is not known, the generator will
  24. pretty much ignore it, but write a comment to the generated code. You
  25. may want to add custom support for this type. In some cases, C++ compile errors
  26. will result. These are intentional - generating code to remove these errors would
  27. imply a false sense of security that the generator has done the right thing.
  28. other return policies -- By default, Python never sees the return SCODE from
  29. a COM function. The interface usually returns None if OK, else a COM exception
  30. if "FAILED(scode)" is TRUE. You may need to change this if:
  31. * EXCEPINFO is passed to the COM function. This is not detected and handled
  32. * For some reason Python should always see the result SCODE, even if it
  33. did fail or succeed. For example, some functions return a BOOLEAN result
  34. in the SCODE, meaning Python should always see it.
  35. * FAILED(scode) for the interface still has valid data to return (by default,
  36. the code generated does not process the return values, and raise an exception
  37. to Python/COM
  38. """
  39. import re
  40. from . import makegwparse
  41. def make_framework_support(header_file_name, interface_name, bMakeInterface = 1, bMakeGateway = 1):
  42. """Generate C++ code for a Python Interface and Gateway
  43. header_file_name -- The full path to the .H file which defines the interface.
  44. interface_name -- The name of the interface to search for, and to generate.
  45. bMakeInterface = 1 -- Should interface (ie, client) support be generated.
  46. bMakeGatewayInterface = 1 -- Should gateway (ie, server) support be generated.
  47. This method will write a .cpp and .h file into the current directory,
  48. (using the name of the interface to build the file name.
  49. """
  50. fin=open(header_file_name)
  51. try:
  52. interface = makegwparse.parse_interface_info(interface_name, fin)
  53. finally:
  54. fin.close()
  55. if bMakeInterface and bMakeGateway:
  56. desc = "Interface and Gateway"
  57. elif bMakeInterface and not bMakeGateway:
  58. desc = "Interface"
  59. else:
  60. desc = "Gateway"
  61. if interface.name[:5]=="IEnum": # IEnum - use my really simple template-based one
  62. import win32com.makegw.makegwenum
  63. ifc_cpp_writer = win32com.makegw.makegwenum._write_enumifc_cpp
  64. gw_cpp_writer = win32com.makegw.makegwenum._write_enumgw_cpp
  65. else: # Use my harder working ones.
  66. ifc_cpp_writer = _write_ifc_cpp
  67. gw_cpp_writer = _write_gw_cpp
  68. fout=open("Py%s.cpp" % interface.name, "w")
  69. try:
  70. fout.write(\
  71. '''\
  72. // This file implements the %s %s for Python.
  73. // Generated by makegw.py
  74. #include "shell_pch.h"
  75. ''' % (interface.name, desc))
  76. # if bMakeGateway:
  77. # fout.write('#include "PythonCOMServer.h"\n')
  78. # if interface.base not in ["IUnknown", "IDispatch"]:
  79. # fout.write('#include "Py%s.h"\n' % interface.base)
  80. fout.write('#include "Py%s.h"\n\n// @doc - This file contains autoduck documentation\n' % interface.name)
  81. if bMakeInterface: ifc_cpp_writer(fout, interface)
  82. if bMakeGateway: gw_cpp_writer(fout, interface)
  83. finally:
  84. fout.close()
  85. fout=open("Py%s.h" % interface.name, "w")
  86. try:
  87. fout.write(\
  88. '''\
  89. // This file declares the %s %s for Python.
  90. // Generated by makegw.py
  91. ''' % (interface.name, desc))
  92. if bMakeInterface: _write_ifc_h(fout, interface)
  93. if bMakeGateway: _write_gw_h(fout, interface)
  94. finally:
  95. fout.close()
  96. ###########################################################################
  97. #
  98. # INTERNAL FUNCTIONS
  99. #
  100. #
  101. def _write_ifc_h(f, interface):
  102. f.write(\
  103. '''\
  104. // ---------------------------------------------------
  105. //
  106. // Interface Declaration
  107. class Py%s : public Py%s
  108. {
  109. public:
  110. MAKE_PYCOM_CTOR(Py%s);
  111. static %s *GetI(PyObject *self);
  112. static PyComTypeObject type;
  113. // The Python methods
  114. ''' % (interface.name, interface.base, interface.name, interface.name))
  115. for method in interface.methods:
  116. f.write('\tstatic PyObject *%s(PyObject *self, PyObject *args);\n' % method.name)
  117. f.write(\
  118. '''\
  119. protected:
  120. Py%s(IUnknown *pdisp);
  121. ~Py%s();
  122. };
  123. ''' % (interface.name, interface.name))
  124. def _write_ifc_cpp(f, interface):
  125. name = interface.name
  126. f.write(\
  127. '''\
  128. // ---------------------------------------------------
  129. //
  130. // Interface Implementation
  131. Py%(name)s::Py%(name)s(IUnknown *pdisp):
  132. Py%(base)s(pdisp)
  133. {
  134. ob_type = &type;
  135. }
  136. Py%(name)s::~Py%(name)s()
  137. {
  138. }
  139. /* static */ %(name)s *Py%(name)s::GetI(PyObject *self)
  140. {
  141. return (%(name)s *)Py%(base)s::GetI(self);
  142. }
  143. ''' % (interface.__dict__))
  144. ptr = re.sub('[a-z]', '', interface.name)
  145. strdict = {'interfacename':interface.name, 'ptr': ptr}
  146. for method in interface.methods:
  147. strdict['method'] = method.name
  148. f.write(\
  149. '''\
  150. // @pymethod |Py%(interfacename)s|%(method)s|Description of %(method)s.
  151. PyObject *Py%(interfacename)s::%(method)s(PyObject *self, PyObject *args)
  152. {
  153. %(interfacename)s *p%(ptr)s = GetI(self);
  154. if ( p%(ptr)s == NULL )
  155. return NULL;
  156. ''' % strdict)
  157. argsParseTuple = argsCOM = formatChars = codePost = \
  158. codePobjects = codeCobjects = cleanup = cleanup_gil = ""
  159. needConversion = 0
  160. # if method.name=="Stat": import win32dbg;win32dbg.brk()
  161. for arg in method.args:
  162. try:
  163. argCvt = makegwparse.make_arg_converter(arg)
  164. if arg.HasAttribute("in"):
  165. val = argCvt.GetFormatChar()
  166. if val:
  167. f.write ('\t' + argCvt.GetAutoduckString() + "\n")
  168. formatChars = formatChars + val
  169. argsParseTuple = argsParseTuple + ", " + argCvt.GetParseTupleArg()
  170. codePobjects = codePobjects + argCvt.DeclareParseArgTupleInputConverter()
  171. codePost = codePost + argCvt.GetParsePostCode()
  172. needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
  173. cleanup = cleanup + argCvt.GetInterfaceArgCleanup()
  174. cleanup_gil = cleanup_gil + argCvt.GetInterfaceArgCleanupGIL()
  175. comArgName, comArgDeclString = argCvt.GetInterfaceCppObjectInfo()
  176. if comArgDeclString: # If we should declare a variable
  177. codeCobjects = codeCobjects + "\t%s;\n" % (comArgDeclString)
  178. argsCOM = argsCOM + ", " + comArgName
  179. except makegwparse.error_not_supported as why:
  180. f.write('// *** The input argument %s of type "%s" was not processed ***\n// Please check the conversion function is appropriate and exists!\n' % (arg.name, arg.raw_type))
  181. f.write('\t%s %s;\n\tPyObject *ob%s;\n' % (arg.type, arg.name, arg.name))
  182. f.write('\t// @pyparm <o Py%s>|%s||Description for %s\n' % (arg.type, arg.name, arg.name))
  183. codePost = codePost + '\tif (bPythonIsHappy && !PyObject_As%s( ob%s, &%s )) bPythonIsHappy = FALSE;\n' % (arg.type, arg.name, arg.name)
  184. formatChars = formatChars + "O"
  185. argsParseTuple = argsParseTuple + ", &ob%s" % (arg.name)
  186. argsCOM = argsCOM + ", " + arg.name
  187. cleanup = cleanup + "\tPyObject_Free%s(%s);\n" % (arg.type, arg.name)
  188. if needConversion: f.write("\tUSES_CONVERSION;\n")
  189. f.write(codePobjects);
  190. f.write(codeCobjects);
  191. f.write('\tif ( !PyArg_ParseTuple(args, "%s:%s"%s) )\n\t\treturn NULL;\n' % (formatChars, method.name, argsParseTuple))
  192. if codePost:
  193. f.write('\tBOOL bPythonIsHappy = TRUE;\n')
  194. f.write(codePost);
  195. f.write('\tif (!bPythonIsHappy) return NULL;\n')
  196. strdict['argsCOM'] = argsCOM[1:]
  197. strdict['cleanup'] = cleanup
  198. strdict['cleanup_gil'] = cleanup_gil
  199. f.write(\
  200. ''' HRESULT hr;
  201. PY_INTERFACE_PRECALL;
  202. hr = p%(ptr)s->%(method)s(%(argsCOM)s );
  203. %(cleanup)s
  204. PY_INTERFACE_POSTCALL;
  205. %(cleanup_gil)s
  206. if ( FAILED(hr) )
  207. return PyCom_BuildPyException(hr, p%(ptr)s, IID_%(interfacename)s );
  208. ''' % strdict)
  209. codePre = codePost = formatChars = codeVarsPass = codeDecl = ""
  210. for arg in method.args:
  211. if not arg.HasAttribute("out"):
  212. continue
  213. try:
  214. argCvt = makegwparse.make_arg_converter(arg)
  215. formatChar = argCvt.GetFormatChar()
  216. if formatChar:
  217. formatChars = formatChars + formatChar
  218. codePre = codePre + argCvt.GetBuildForInterfacePreCode()
  219. codePost = codePost + argCvt.GetBuildForInterfacePostCode()
  220. codeVarsPass = codeVarsPass + ", " + argCvt.GetBuildValueArg()
  221. codeDecl = codeDecl + argCvt.DeclareParseArgTupleInputConverter()
  222. except makegwparse.error_not_supported as why:
  223. f.write('// *** The output argument %s of type "%s" was not processed ***\n// %s\n' % (arg.name, arg.raw_type, why))
  224. continue
  225. if formatChars:
  226. f.write('%s\n%s\tPyObject *pyretval = Py_BuildValue("%s"%s);\n%s\treturn pyretval;' % (codeDecl, codePre, formatChars, codeVarsPass, codePost))
  227. else:
  228. f.write('\tPy_INCREF(Py_None);\n\treturn Py_None;\n')
  229. f.write('\n}\n\n')
  230. f.write ('// @object Py%s|Description of the interface\n' % (name))
  231. f.write('static struct PyMethodDef Py%s_methods[] =\n{\n' % name)
  232. for method in interface.methods:
  233. f.write('\t{ "%s", Py%s::%s, 1 }, // @pymeth %s|Description of %s\n' % (method.name, interface.name, method.name, method.name, method.name))
  234. interfacebase = interface.base
  235. f.write('''\
  236. { NULL }
  237. };
  238. PyComTypeObject Py%(name)s::type("Py%(name)s",
  239. &Py%(interfacebase)s::type,
  240. sizeof(Py%(name)s),
  241. Py%(name)s_methods,
  242. GET_PYCOM_CTOR(Py%(name)s));
  243. ''' % locals())
  244. def _write_gw_h(f, interface):
  245. if interface.name[0] == "I":
  246. gname = 'PyG' + interface.name[1:]
  247. else:
  248. gname = 'PyG' + interface.name
  249. name = interface.name
  250. if interface.base == "IUnknown" or interface.base == "IDispatch":
  251. base_name = "PyGatewayBase"
  252. else:
  253. if interface.base[0] == "I":
  254. base_name = 'PyG' + interface.base[1:]
  255. else:
  256. base_name = 'PyG' + interface.base
  257. f.write(\
  258. '''\
  259. // ---------------------------------------------------
  260. //
  261. // Gateway Declaration
  262. class %s : public %s, public %s
  263. {
  264. protected:
  265. %s(PyObject *instance) : %s(instance) { ; }
  266. PYGATEWAY_MAKE_SUPPORT2(%s, %s, IID_%s, %s)
  267. ''' % (gname, base_name, name, gname, base_name, gname, name, name, base_name))
  268. if interface.base != "IUnknown":
  269. f.write("\t// %s\n\t// *** Manually add %s method decls here\n\n" % (interface.base, interface.base))
  270. else:
  271. f.write('\n\n')
  272. f.write("\t// %s\n" % name)
  273. for method in interface.methods:
  274. f.write('\tSTDMETHOD(%s)(\n' % method.name)
  275. if method.args:
  276. for arg in method.args[:-1]:
  277. f.write("\t\t%s,\n" % (arg.GetRawDeclaration()))
  278. arg = method.args[-1]
  279. f.write("\t\t%s);\n\n" % (arg.GetRawDeclaration()))
  280. else:
  281. f.write('\t\tvoid);\n\n')
  282. f.write('};\n')
  283. f.close()
  284. def _write_gw_cpp(f, interface):
  285. if interface.name[0] == "I":
  286. gname = 'PyG' + interface.name[1:]
  287. else:
  288. gname = 'PyG' + interface.name
  289. name = interface.name
  290. if interface.base == "IUnknown" or interface.base == "IDispatch":
  291. base_name = "PyGatewayBase"
  292. else:
  293. if interface.base[0] == "I":
  294. base_name = 'PyG' + interface.base[1:]
  295. else:
  296. base_name = 'PyG' + interface.base
  297. f.write('''\
  298. // ---------------------------------------------------
  299. //
  300. // Gateway Implementation
  301. ''' % {'name':name, 'gname':gname, 'base_name':base_name})
  302. for method in interface.methods:
  303. f.write(\
  304. '''\
  305. STDMETHODIMP %s::%s(
  306. ''' % (gname, method.name))
  307. if method.args:
  308. for arg in method.args[:-1]:
  309. inoutstr = ']['.join(arg.inout)
  310. f.write("\t\t/* [%s] */ %s,\n" % (inoutstr, arg.GetRawDeclaration()))
  311. arg = method.args[-1]
  312. inoutstr = ']['.join(arg.inout)
  313. f.write("\t\t/* [%s] */ %s)\n" % (inoutstr, arg.GetRawDeclaration()))
  314. else:
  315. f.write('\t\tvoid)\n')
  316. f.write("{\n\tPY_GATEWAY_METHOD;\n")
  317. cout = 0
  318. codePre = codePost = codeVars = ""
  319. argStr = ""
  320. needConversion = 0
  321. formatChars = ""
  322. if method.args:
  323. for arg in method.args:
  324. if arg.HasAttribute("out"):
  325. cout = cout + 1
  326. if arg.indirectionLevel ==2 :
  327. f.write("\tif (%s==NULL) return E_POINTER;\n" % arg.name)
  328. if arg.HasAttribute("in"):
  329. try:
  330. argCvt = makegwparse.make_arg_converter(arg)
  331. argCvt.SetGatewayMode()
  332. formatchar = argCvt.GetFormatChar();
  333. needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
  334. if formatchar:
  335. formatChars = formatChars + formatchar
  336. codeVars = codeVars + argCvt.DeclareParseArgTupleInputConverter()
  337. argStr = argStr + ", " + argCvt.GetBuildValueArg()
  338. codePre = codePre + argCvt.GetBuildForGatewayPreCode()
  339. codePost = codePost + argCvt.GetBuildForGatewayPostCode()
  340. except makegwparse.error_not_supported as why:
  341. f.write('// *** The input argument %s of type "%s" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - %s\n' % (arg.name, arg.raw_type, why))
  342. f.write('\tPyObject *ob%s = PyObject_From%s(%s);\n' % (arg.name, arg.type, arg.name))
  343. f.write('\tif (ob%s==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n' % (arg.name, method.name))
  344. codePost = codePost + "\tPy_DECREF(ob%s);\n" % arg.name
  345. formatChars = formatChars + "O"
  346. argStr = argStr + ", ob%s" % (arg.name)
  347. if needConversion: f.write('\tUSES_CONVERSION;\n')
  348. f.write(codeVars)
  349. f.write(codePre)
  350. if cout:
  351. f.write("\tPyObject *result;\n")
  352. resStr = "&result"
  353. else:
  354. resStr = "NULL"
  355. if formatChars:
  356. fullArgStr = '%s, "%s"%s' % (resStr, formatChars, argStr)
  357. else:
  358. fullArgStr = resStr
  359. f.write('\tHRESULT hr=InvokeViaPolicy("%s", %s);\n' % (method.name, fullArgStr))
  360. f.write(codePost)
  361. if cout:
  362. f.write("\tif (FAILED(hr)) return hr;\n")
  363. f.write("\t// Process the Python results, and convert back to the real params\n")
  364. # process the output arguments.
  365. formatChars = codePobjects = codePost = argsParseTuple = ""
  366. needConversion = 0
  367. for arg in method.args:
  368. if not arg.HasAttribute("out"):
  369. continue
  370. try:
  371. argCvt = makegwparse.make_arg_converter(arg)
  372. argCvt.SetGatewayMode()
  373. val = argCvt.GetFormatChar()
  374. if val:
  375. formatChars = formatChars + val
  376. argsParseTuple = argsParseTuple + ", " + argCvt.GetParseTupleArg()
  377. codePobjects = codePobjects + argCvt.DeclareParseArgTupleInputConverter()
  378. codePost = codePost + argCvt.GetParsePostCode()
  379. needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
  380. except makegwparse.error_not_supported as why:
  381. f.write('// *** The output argument %s of type "%s" was not processed ***\n// %s\n' % (arg.name, arg.raw_type, why))
  382. if formatChars: # If I have any to actually process.
  383. if len(formatChars)==1:
  384. parseFn = "PyArg_Parse"
  385. else:
  386. parseFn = "PyArg_ParseTuple"
  387. if codePobjects: f.write(codePobjects)
  388. f.write('\tif (!%s(result, "%s" %s))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n' % (parseFn, formatChars, argsParseTuple, method.name))
  389. if codePost:
  390. f.write('\tBOOL bPythonIsHappy = TRUE;\n')
  391. f.write(codePost)
  392. f.write('\tif (!bPythonIsHappy) hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n' % method.name)
  393. f.write('\tPy_DECREF(result);\n');
  394. f.write('\treturn hr;\n}\n\n')
  395. def test():
  396. # make_framework_support("d:\\msdev\\include\\objidl.h", "ILockBytes")
  397. make_framework_support("d:\\msdev\\include\\objidl.h", "IStorage")
  398. # make_framework_support("d:\\msdev\\include\\objidl.h", "IEnumSTATSTG")