Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

makegw.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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(
  42. header_file_name, interface_name, bMakeInterface=1, bMakeGateway=1
  43. ):
  44. """Generate C++ code for a Python Interface and Gateway
  45. header_file_name -- The full path to the .H file which defines the interface.
  46. interface_name -- The name of the interface to search for, and to generate.
  47. bMakeInterface = 1 -- Should interface (ie, client) support be generated.
  48. bMakeGatewayInterface = 1 -- Should gateway (ie, server) support be generated.
  49. This method will write a .cpp and .h file into the current directory,
  50. (using the name of the interface to build the file name.
  51. """
  52. fin = open(header_file_name)
  53. try:
  54. interface = makegwparse.parse_interface_info(interface_name, fin)
  55. finally:
  56. fin.close()
  57. if bMakeInterface and bMakeGateway:
  58. desc = "Interface and Gateway"
  59. elif bMakeInterface and not bMakeGateway:
  60. desc = "Interface"
  61. else:
  62. desc = "Gateway"
  63. if interface.name[:5] == "IEnum": # IEnum - use my really simple template-based one
  64. import win32com.makegw.makegwenum
  65. ifc_cpp_writer = win32com.makegw.makegwenum._write_enumifc_cpp
  66. gw_cpp_writer = win32com.makegw.makegwenum._write_enumgw_cpp
  67. else: # Use my harder working ones.
  68. ifc_cpp_writer = _write_ifc_cpp
  69. gw_cpp_writer = _write_gw_cpp
  70. fout = open("Py%s.cpp" % interface.name, "w")
  71. try:
  72. fout.write(
  73. """\
  74. // This file implements the %s %s for Python.
  75. // Generated by makegw.py
  76. #include "shell_pch.h"
  77. """
  78. % (interface.name, desc)
  79. )
  80. # if bMakeGateway:
  81. # fout.write('#include "PythonCOMServer.h"\n')
  82. # if interface.base not in ["IUnknown", "IDispatch"]:
  83. # fout.write('#include "Py%s.h"\n' % interface.base)
  84. fout.write(
  85. '#include "Py%s.h"\n\n// @doc - This file contains autoduck documentation\n'
  86. % interface.name
  87. )
  88. if bMakeInterface:
  89. ifc_cpp_writer(fout, interface)
  90. if bMakeGateway:
  91. gw_cpp_writer(fout, interface)
  92. finally:
  93. fout.close()
  94. fout = open("Py%s.h" % interface.name, "w")
  95. try:
  96. fout.write(
  97. """\
  98. // This file declares the %s %s for Python.
  99. // Generated by makegw.py
  100. """
  101. % (interface.name, desc)
  102. )
  103. if bMakeInterface:
  104. _write_ifc_h(fout, interface)
  105. if bMakeGateway:
  106. _write_gw_h(fout, interface)
  107. finally:
  108. fout.close()
  109. ###########################################################################
  110. #
  111. # INTERNAL FUNCTIONS
  112. #
  113. #
  114. def _write_ifc_h(f, interface):
  115. f.write(
  116. """\
  117. // ---------------------------------------------------
  118. //
  119. // Interface Declaration
  120. class Py%s : public Py%s
  121. {
  122. public:
  123. MAKE_PYCOM_CTOR(Py%s);
  124. static %s *GetI(PyObject *self);
  125. static PyComTypeObject type;
  126. // The Python methods
  127. """
  128. % (interface.name, interface.base, interface.name, interface.name)
  129. )
  130. for method in interface.methods:
  131. f.write(
  132. "\tstatic PyObject *%s(PyObject *self, PyObject *args);\n" % method.name
  133. )
  134. f.write(
  135. """\
  136. protected:
  137. Py%s(IUnknown *pdisp);
  138. ~Py%s();
  139. };
  140. """
  141. % (interface.name, interface.name)
  142. )
  143. def _write_ifc_cpp(f, interface):
  144. name = interface.name
  145. f.write(
  146. """\
  147. // ---------------------------------------------------
  148. //
  149. // Interface Implementation
  150. Py%(name)s::Py%(name)s(IUnknown *pdisp):
  151. Py%(base)s(pdisp)
  152. {
  153. ob_type = &type;
  154. }
  155. Py%(name)s::~Py%(name)s()
  156. {
  157. }
  158. /* static */ %(name)s *Py%(name)s::GetI(PyObject *self)
  159. {
  160. return (%(name)s *)Py%(base)s::GetI(self);
  161. }
  162. """
  163. % (interface.__dict__)
  164. )
  165. ptr = re.sub("[a-z]", "", interface.name)
  166. strdict = {"interfacename": interface.name, "ptr": ptr}
  167. for method in interface.methods:
  168. strdict["method"] = method.name
  169. f.write(
  170. """\
  171. // @pymethod |Py%(interfacename)s|%(method)s|Description of %(method)s.
  172. PyObject *Py%(interfacename)s::%(method)s(PyObject *self, PyObject *args)
  173. {
  174. %(interfacename)s *p%(ptr)s = GetI(self);
  175. if ( p%(ptr)s == NULL )
  176. return NULL;
  177. """
  178. % strdict
  179. )
  180. argsParseTuple = (
  181. argsCOM
  182. ) = (
  183. formatChars
  184. ) = codePost = codePobjects = codeCobjects = cleanup = cleanup_gil = ""
  185. needConversion = 0
  186. # if method.name=="Stat": import win32dbg;win32dbg.brk()
  187. for arg in method.args:
  188. try:
  189. argCvt = makegwparse.make_arg_converter(arg)
  190. if arg.HasAttribute("in"):
  191. val = argCvt.GetFormatChar()
  192. if val:
  193. f.write("\t" + argCvt.GetAutoduckString() + "\n")
  194. formatChars = formatChars + val
  195. argsParseTuple = (
  196. argsParseTuple + ", " + argCvt.GetParseTupleArg()
  197. )
  198. codePobjects = (
  199. codePobjects + argCvt.DeclareParseArgTupleInputConverter()
  200. )
  201. codePost = codePost + argCvt.GetParsePostCode()
  202. needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
  203. cleanup = cleanup + argCvt.GetInterfaceArgCleanup()
  204. cleanup_gil = cleanup_gil + argCvt.GetInterfaceArgCleanupGIL()
  205. comArgName, comArgDeclString = argCvt.GetInterfaceCppObjectInfo()
  206. if comArgDeclString: # If we should declare a variable
  207. codeCobjects = codeCobjects + "\t%s;\n" % (comArgDeclString)
  208. argsCOM = argsCOM + ", " + comArgName
  209. except makegwparse.error_not_supported as why:
  210. f.write(
  211. '// *** The input argument %s of type "%s" was not processed ***\n// Please check the conversion function is appropriate and exists!\n'
  212. % (arg.name, arg.raw_type)
  213. )
  214. f.write(
  215. "\t%s %s;\n\tPyObject *ob%s;\n" % (arg.type, arg.name, arg.name)
  216. )
  217. f.write(
  218. "\t// @pyparm <o Py%s>|%s||Description for %s\n"
  219. % (arg.type, arg.name, arg.name)
  220. )
  221. codePost = (
  222. codePost
  223. + "\tif (bPythonIsHappy && !PyObject_As%s( ob%s, &%s )) bPythonIsHappy = FALSE;\n"
  224. % (arg.type, arg.name, arg.name)
  225. )
  226. formatChars = formatChars + "O"
  227. argsParseTuple = argsParseTuple + ", &ob%s" % (arg.name)
  228. argsCOM = argsCOM + ", " + arg.name
  229. cleanup = cleanup + "\tPyObject_Free%s(%s);\n" % (arg.type, arg.name)
  230. if needConversion:
  231. f.write("\tUSES_CONVERSION;\n")
  232. f.write(codePobjects)
  233. f.write(codeCobjects)
  234. f.write(
  235. '\tif ( !PyArg_ParseTuple(args, "%s:%s"%s) )\n\t\treturn NULL;\n'
  236. % (formatChars, method.name, argsParseTuple)
  237. )
  238. if codePost:
  239. f.write("\tBOOL bPythonIsHappy = TRUE;\n")
  240. f.write(codePost)
  241. f.write("\tif (!bPythonIsHappy) return NULL;\n")
  242. strdict["argsCOM"] = argsCOM[1:]
  243. strdict["cleanup"] = cleanup
  244. strdict["cleanup_gil"] = cleanup_gil
  245. f.write(
  246. """ HRESULT hr;
  247. PY_INTERFACE_PRECALL;
  248. hr = p%(ptr)s->%(method)s(%(argsCOM)s );
  249. %(cleanup)s
  250. PY_INTERFACE_POSTCALL;
  251. %(cleanup_gil)s
  252. if ( FAILED(hr) )
  253. return PyCom_BuildPyException(hr, p%(ptr)s, IID_%(interfacename)s );
  254. """
  255. % strdict
  256. )
  257. codePre = codePost = formatChars = codeVarsPass = codeDecl = ""
  258. for arg in method.args:
  259. if not arg.HasAttribute("out"):
  260. continue
  261. try:
  262. argCvt = makegwparse.make_arg_converter(arg)
  263. formatChar = argCvt.GetFormatChar()
  264. if formatChar:
  265. formatChars = formatChars + formatChar
  266. codePre = codePre + argCvt.GetBuildForInterfacePreCode()
  267. codePost = codePost + argCvt.GetBuildForInterfacePostCode()
  268. codeVarsPass = codeVarsPass + ", " + argCvt.GetBuildValueArg()
  269. codeDecl = codeDecl + argCvt.DeclareParseArgTupleInputConverter()
  270. except makegwparse.error_not_supported as why:
  271. f.write(
  272. '// *** The output argument %s of type "%s" was not processed ***\n// %s\n'
  273. % (arg.name, arg.raw_type, why)
  274. )
  275. continue
  276. if formatChars:
  277. f.write(
  278. '%s\n%s\tPyObject *pyretval = Py_BuildValue("%s"%s);\n%s\treturn pyretval;'
  279. % (codeDecl, codePre, formatChars, codeVarsPass, codePost)
  280. )
  281. else:
  282. f.write("\tPy_INCREF(Py_None);\n\treturn Py_None;\n")
  283. f.write("\n}\n\n")
  284. f.write("// @object Py%s|Description of the interface\n" % (name))
  285. f.write("static struct PyMethodDef Py%s_methods[] =\n{\n" % name)
  286. for method in interface.methods:
  287. f.write(
  288. '\t{ "%s", Py%s::%s, 1 }, // @pymeth %s|Description of %s\n'
  289. % (method.name, interface.name, method.name, method.name, method.name)
  290. )
  291. interfacebase = interface.base
  292. f.write(
  293. """\
  294. { NULL }
  295. };
  296. PyComTypeObject Py%(name)s::type("Py%(name)s",
  297. &Py%(interfacebase)s::type,
  298. sizeof(Py%(name)s),
  299. Py%(name)s_methods,
  300. GET_PYCOM_CTOR(Py%(name)s));
  301. """
  302. % locals()
  303. )
  304. def _write_gw_h(f, interface):
  305. if interface.name[0] == "I":
  306. gname = "PyG" + interface.name[1:]
  307. else:
  308. gname = "PyG" + interface.name
  309. name = interface.name
  310. if interface.base == "IUnknown" or interface.base == "IDispatch":
  311. base_name = "PyGatewayBase"
  312. else:
  313. if interface.base[0] == "I":
  314. base_name = "PyG" + interface.base[1:]
  315. else:
  316. base_name = "PyG" + interface.base
  317. f.write(
  318. """\
  319. // ---------------------------------------------------
  320. //
  321. // Gateway Declaration
  322. class %s : public %s, public %s
  323. {
  324. protected:
  325. %s(PyObject *instance) : %s(instance) { ; }
  326. PYGATEWAY_MAKE_SUPPORT2(%s, %s, IID_%s, %s)
  327. """
  328. % (gname, base_name, name, gname, base_name, gname, name, name, base_name)
  329. )
  330. if interface.base != "IUnknown":
  331. f.write(
  332. "\t// %s\n\t// *** Manually add %s method decls here\n\n"
  333. % (interface.base, interface.base)
  334. )
  335. else:
  336. f.write("\n\n")
  337. f.write("\t// %s\n" % name)
  338. for method in interface.methods:
  339. f.write("\tSTDMETHOD(%s)(\n" % method.name)
  340. if method.args:
  341. for arg in method.args[:-1]:
  342. f.write("\t\t%s,\n" % (arg.GetRawDeclaration()))
  343. arg = method.args[-1]
  344. f.write("\t\t%s);\n\n" % (arg.GetRawDeclaration()))
  345. else:
  346. f.write("\t\tvoid);\n\n")
  347. f.write("};\n")
  348. f.close()
  349. def _write_gw_cpp(f, interface):
  350. if interface.name[0] == "I":
  351. gname = "PyG" + interface.name[1:]
  352. else:
  353. gname = "PyG" + interface.name
  354. name = interface.name
  355. if interface.base == "IUnknown" or interface.base == "IDispatch":
  356. base_name = "PyGatewayBase"
  357. else:
  358. if interface.base[0] == "I":
  359. base_name = "PyG" + interface.base[1:]
  360. else:
  361. base_name = "PyG" + interface.base
  362. f.write(
  363. """\
  364. // ---------------------------------------------------
  365. //
  366. // Gateway Implementation
  367. """
  368. % {"name": name, "gname": gname, "base_name": base_name}
  369. )
  370. for method in interface.methods:
  371. f.write(
  372. """\
  373. STDMETHODIMP %s::%s(
  374. """
  375. % (gname, method.name)
  376. )
  377. if method.args:
  378. for arg in method.args[:-1]:
  379. inoutstr = "][".join(arg.inout)
  380. f.write("\t\t/* [%s] */ %s,\n" % (inoutstr, arg.GetRawDeclaration()))
  381. arg = method.args[-1]
  382. inoutstr = "][".join(arg.inout)
  383. f.write("\t\t/* [%s] */ %s)\n" % (inoutstr, arg.GetRawDeclaration()))
  384. else:
  385. f.write("\t\tvoid)\n")
  386. f.write("{\n\tPY_GATEWAY_METHOD;\n")
  387. cout = 0
  388. codePre = codePost = codeVars = ""
  389. argStr = ""
  390. needConversion = 0
  391. formatChars = ""
  392. if method.args:
  393. for arg in method.args:
  394. if arg.HasAttribute("out"):
  395. cout = cout + 1
  396. if arg.indirectionLevel == 2:
  397. f.write("\tif (%s==NULL) return E_POINTER;\n" % arg.name)
  398. if arg.HasAttribute("in"):
  399. try:
  400. argCvt = makegwparse.make_arg_converter(arg)
  401. argCvt.SetGatewayMode()
  402. formatchar = argCvt.GetFormatChar()
  403. needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
  404. if formatchar:
  405. formatChars = formatChars + formatchar
  406. codeVars = (
  407. codeVars + argCvt.DeclareParseArgTupleInputConverter()
  408. )
  409. argStr = argStr + ", " + argCvt.GetBuildValueArg()
  410. codePre = codePre + argCvt.GetBuildForGatewayPreCode()
  411. codePost = codePost + argCvt.GetBuildForGatewayPostCode()
  412. except makegwparse.error_not_supported as why:
  413. f.write(
  414. '// *** The input argument %s of type "%s" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - %s\n'
  415. % (arg.name, arg.raw_type, why)
  416. )
  417. f.write(
  418. "\tPyObject *ob%s = PyObject_From%s(%s);\n"
  419. % (arg.name, arg.type, arg.name)
  420. )
  421. f.write(
  422. '\tif (ob%s==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n'
  423. % (arg.name, method.name)
  424. )
  425. codePost = codePost + "\tPy_DECREF(ob%s);\n" % arg.name
  426. formatChars = formatChars + "O"
  427. argStr = argStr + ", ob%s" % (arg.name)
  428. if needConversion:
  429. f.write("\tUSES_CONVERSION;\n")
  430. f.write(codeVars)
  431. f.write(codePre)
  432. if cout:
  433. f.write("\tPyObject *result;\n")
  434. resStr = "&result"
  435. else:
  436. resStr = "NULL"
  437. if formatChars:
  438. fullArgStr = '%s, "%s"%s' % (resStr, formatChars, argStr)
  439. else:
  440. fullArgStr = resStr
  441. f.write('\tHRESULT hr=InvokeViaPolicy("%s", %s);\n' % (method.name, fullArgStr))
  442. f.write(codePost)
  443. if cout:
  444. f.write("\tif (FAILED(hr)) return hr;\n")
  445. f.write(
  446. "\t// Process the Python results, and convert back to the real params\n"
  447. )
  448. # process the output arguments.
  449. formatChars = codePobjects = codePost = argsParseTuple = ""
  450. needConversion = 0
  451. for arg in method.args:
  452. if not arg.HasAttribute("out"):
  453. continue
  454. try:
  455. argCvt = makegwparse.make_arg_converter(arg)
  456. argCvt.SetGatewayMode()
  457. val = argCvt.GetFormatChar()
  458. if val:
  459. formatChars = formatChars + val
  460. argsParseTuple = (
  461. argsParseTuple + ", " + argCvt.GetParseTupleArg()
  462. )
  463. codePobjects = (
  464. codePobjects + argCvt.DeclareParseArgTupleInputConverter()
  465. )
  466. codePost = codePost + argCvt.GetParsePostCode()
  467. needConversion = needConversion or argCvt.NeedUSES_CONVERSION()
  468. except makegwparse.error_not_supported as why:
  469. f.write(
  470. '// *** The output argument %s of type "%s" was not processed ***\n// %s\n'
  471. % (arg.name, arg.raw_type, why)
  472. )
  473. if formatChars: # If I have any to actually process.
  474. if len(formatChars) == 1:
  475. parseFn = "PyArg_Parse"
  476. else:
  477. parseFn = "PyArg_ParseTuple"
  478. if codePobjects:
  479. f.write(codePobjects)
  480. f.write(
  481. '\tif (!%s(result, "%s" %s))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n'
  482. % (parseFn, formatChars, argsParseTuple, method.name)
  483. )
  484. if codePost:
  485. f.write("\tBOOL bPythonIsHappy = TRUE;\n")
  486. f.write(codePost)
  487. f.write(
  488. '\tif (!bPythonIsHappy) hr = MAKE_PYCOM_GATEWAY_FAILURE_CODE("%s");\n'
  489. % method.name
  490. )
  491. f.write("\tPy_DECREF(result);\n")
  492. f.write("\treturn hr;\n}\n\n")
  493. def test():
  494. # make_framework_support("d:\\msdev\\include\\objidl.h", "ILockBytes")
  495. make_framework_support("d:\\msdev\\include\\objidl.h", "IStorage")
  496. # make_framework_support("d:\\msdev\\include\\objidl.h", "IEnumSTATSTG")